什么是react按需加载?简单来说就是当我们引用antd的时候需要引入全局css样式,这会对性能造成一定的影响,那么使用按需加载以后就不需要引入css全局样式了,直接引入功能模块即可,既然需要设置按需加载就要对webpack文件进行修改,需要我们执行npm run eject命令来展开项目的隐藏文件,如果只是简单的修改,我们可以使用react-app-rewired定义全局变量,react-app-rewired的作用就是在不eject的情况下,覆盖create-react-app的配置。具体如下:
使用 react-app-rewired 对 create-react-app 的默认配置进行自定义
1.yarn add react-app-rewired --dev
/* 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 --env=jsdom", + "test": "react-app-rewired test --env=jsdom", }
2.然后在项目根目录创建一个config-overrides.js用于修改默认配置
module.exports = function override(config, env) { // do stuff with the webpack config... return config; };
使用babel-plugin-import
babel-plugin-import 是一个用于按需加载组件代码和样式babel 插件(原理),现在我们尝试安装它并修改config-overrides.js
文件
1.yarn add babel-plugin-import --dev
+ const { injectBabelPlugin } = require('react-app-rewired'); module.exports = function override(config, env) { + config = injectBabelPlugin(['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }], config); return config; };
或者也可以修改
{ test: /.(js|jsx|mjs)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { plugins: [ // 引入样式为 'css' // style为true 则默认引入less ['import', { libraryName: 'antd', style: true }], ], // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true, }, },
参考链接:https://ant.design/docs/react/use-with-create-react-app-cn