最新版react16.9中按需加载antd和使用less

使用create-react-app创建应用

yarn create react-app my-app

cd my-app

yarn start

引入 antd

这是 create-react-app 生成的默认目录结构。

├── README.md
├── package.json
├── public
│   ├── favicon.ico
│   └── index.html
├── src
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── index.css
│   ├── index.js
│   └── logo.svg
└── yarn.lock

现在从 yarn 或 npm 安装并引入 antd。

yarn add antd

按需加载

引入react-app-rewired ,这是一个可以自定义react项目配置的库, 对于使用Webpack 4的create-react-app 2.x:

yarn add react-app-rewired --dev

由于新的 react-app-rewired@2.x 版本的关系,需要安装 customize-cra

yarn add customize-cra --dev

修改package.json项目启动项

/* package.json */

// 旧的
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

// 替换
"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test"
},

安装babel-plugin-import插件

babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件(原理),在项目根目录创建一个 config-overrides.js 用于修改默认配置。添加以下内容:


const { override, fixBabelImports } = require('customize-cra');

module.exports = override(
    fixBabelImports('import', {
        libraryName: 'antd',
        libraryDirectory: 'es',
        style: 'css',
    }),
);

使用less

yarn add less less-loader --dev

修改config-overrides.js文件,添加以下内容:

-  const { override, fixBabelImports } = require('customize-cra');
+ const { override, fixBabelImports,addLessLoader } = require('customize-cra');

module.exports = override(
    fixBabelImports('import', {
        libraryName: 'antd',
        libraryDirectory: 'es',
        style: 'css',
    }),
 + addLessLoader({        
 +     javascriptEnabled: true,        
 +     modifyVars: { 
 +       '@primary-color': '#1DA57A' 
 +     }    
 +  })
);

使用scss

scss无需配置,安装插件即可使用

yarn add node-sass sass-loader --dev

修改 src/App.js,引入 antd 的按钮组件。

import React, { Component } from 'react';
import Button from 'antd/es/button';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Button type="primary">Button</Button>
      </div>
    );
  }
}

export default App;

修改src/App.css为 App.less

.App {
  text-align: center;
}
.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
  .App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 40vmin;
  pointer-events: none;
  }
  .App-link {
  color: #61dafb;
  }
}

最后 yarn start启动项目

参考资料: 使用react-app-rewired和customize-cra对默认设置自定义

原文地址:https://www.cnblogs.com/dobeco/p/11295178.html