使用 create-react-app 建立的 react 项目,结合使用 antd 时,官网文档介绍了按需加载须要使用 babel-plugin-import 来配合,若是你的项目尚未执行 npm run eject
,则使用官网推荐的配置便可,因为我已经 eject
过,记录下个人配置。javascript
yarn add babel-plugin-import
或者 npm -s install babel-plugin-import
babel-loader
plugins 加上 babel-plugin-import
须要修改两个文件 /config/webpack.config.prod.js
和 /config/webpack.config.dev.js
(修改的内容同样),找到加载 babel-loader
的地方,往他的 plugins 加入以下代码css
[
require.resolve('babel-plugin-import'),// 导入 import 插件
{
libraryName: 'antd', //暴露antd
style: 'css'
}
]
复制代码
最后造成的配置以下(create-react-app 版本不一样最后的配置可能不同,原理同样):java
// Process application JS with Babel.
// The preset includes JSX, Flow, 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?-prettier,-svgo![path]',
},
},
},
],
[
require.resolve('babel-plugin-import'),// 导入 import 插件
{
libraryName: 'antd', //暴露antd
style: 'css'
}
],
],
// 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,
// Don't waste time on Gzipping the cache
cacheCompression: false,
},
}
复制代码