用create-react-app 创建一个项目后,由于要用到 Antd 想要按需加载,安装官网文档介绍,下载 babel-plugin-import 插件后
然后在项目根目录 添加 .babelrc 文件
// .babelrc
{
"plugins": [
["import", {
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css" // `style: true` 会加载 less 文件
}]
]
}
测试后,样式无效。
在 package.json 文件中添加
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css"
}
]
]
}
测试后,样式还是不生效
都不生效,那我想在webpack里面改,npm run eject 暴露 webpack 配置
发现 package.json 文件下面自带有 babel 配置
// package.json
"babel": {
"presets": [
"react-app"
]
}
// 修改为
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css"
}
]
]
}
哎嘿,样式生效了!!!
然后又试下了 webpack 配置
// webpack.config.js
{
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,+titleProp,+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,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction
}
},
// 修改为
{
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,+titleProp,+ref![path]"
}
}
}
],
[
"import",
{
libraryName: "antd",
libraryDirectory: "es",
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,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction
}
},
同样,样式可以生效。
最后测试了下,添加 .babelrc 文件,报错,看了下配置是把 babelrc 禁用掉了,如何配置 babelrc ,各位童鞋自行研究哈。
至此,能够实现 antd 按需加载的,配置方法如下:
首先要 npm run eject
方法1:
在 package.json 的 babel 属性下添加
"plugins": [
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css"
}
]
]
方法2:
在 webpack.config.js 中 babel-loader 的 options 下面的 plugins 添加
["import", {
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css" // `style: true` 会加载 less 文件
}
]
现在可以实现 antd 的按需加载了。