按照官网在create-react-app中使用(官网链接):
截图:
如此操作完成后,我的antd确实是可以按需加载了。
但是我又使用了antd-mobile,那么这个antd-mobile要如何按需加载?
这时就要修改到配置文件了,首先要使用eject将配置文件暴露出来。
运行yarn run eject命令(先将之前的文件提交到git中)
然后要修改package.json文件的scripts成如下:
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js"
},
接着将package.json的
"babel": {
"presets": [
"react-app"
],
}
改成:
"babel": {
"presets": [
"react-app"
],
"plugins": [
["import", { "libraryName": "antd", "style": "css"}, "ant"],
["import", { "libraryName": "antd-mobile", "style": "css"}, "antd-mobile"]
]
}
也就是添加了plugins,终于将antd和antd-mobile都能按需加载了。
看朋友们都是这么为antd按需加载的(记录,并没有使用这种方式):
eject#
你也可以使用 create-react-app 提供的 yarn run eject 命令将所有内建的配置暴露出来。不过这种配置方式需要你自行探索,不在本文讨论范围内。
使用这个命令将会在根目录下生成一个config目录,有一个文件webpack.config.dev.js,
修改:
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent: '@svgr/webpack?-svgo,+ref![path]',
},
},
},
],
],
// 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,
cacheCompression: isEnvProduction,
compact: isEnvProduction,
},
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
"plugins": [
["import", { libraryName: "antd", style: "css" }] // `style: true` 会加载 less 文件
],
// 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,
},
},