按需导入antd

  1. yarn add babel-plugin-import
  2. yarn add react-app-rewired customize-cra
  3. 修改package.json
"scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test",
+   "test": "react-app-rewired test",
}
  1. 在项目根目录创建一个 config-overrides.js 用于修改默认配置。
module.exports = function override(config, env) {
  // do stuff with the webpack config...
  return config;
};

此时就实现按需加载了,
然后只需从 antd 引入模块即可,无需单独引入样式。
例如:

import { Button } from 'antd';

此方法比运行yarn eject的方法好在不会暴露所有的配置文件
注:
若项目运行后,报错:The “injectBabelPlugin” helper has been deprecated as of v2.0. You can use customize-cra plugins in replacement - https://github.com/arackaf/customize-c
ra#available-plugins
进到这里https://github.com/arackaf/customize-cra#available-plugins
,就看到一句话:Override webpack configurations for create-react-app 2.0,react-scripts 升级到 2.1.2 以后破坏了 react-app-rewired,react-app-rewired的新版本删除所有方法injectBabelPlugin,这些方法被移动到一个名为’customize-cra’的新包中了

yarn add customize-cra --dev
yarn add less
yarn add --dev less-loader

下载完,修改下config-overrides.js

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


module.exports = override(
    fixBabelImports("import", {
        libraryName: "antd", libraryDirectory: "es", style: 'css' // change importing css to less
    }),
);

你可能感兴趣的:(react)