antd按需加载配置过程
安装模块
yarn add react-app-rewired customize-cra babel-plugin-import
修改 package.json 里的启动配置
/* package.json */
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test"
}
项目根目录创建一个 config-overrides.js 用于修改默认配置。
const { override, fixBabelImports } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
);
重启启动项目
启动之前先移除前面在 src/App.css 里全量添加的 @import ‘~antd/dist/antd.css’; ,然后yarn start 运行项目,如果报错:
yarn start
module.js:550
throw err;
^
Error: Cannot find module 'react-scripts/package.json'
at Function.Module._resolveFilename (module.js:548:15)
at Function.resolve (internal/module.js:18:19)
at Object.<anonymous> (D:\project\pb-antd\node_modules\react-app-rewired\scripts\utils\paths.js:25:11)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
解决办法:将 react-scripts添加到依赖中
yarn add react-scripts --dev