下载antd:
npm i antd -S
安装babel-plugin-import:
npm i babel-plugin-import -S
然后在.babelrc中添加如下代码:
// .babelrc or babel-loader option
{
"plugins": [
["import", { libraryName: "antd", style: "css" }] // `style: true` 会加载 less 文件
]
}
但如果是用的create-react-app脚手架的话,初始的根目录里并没有.babelrc文件,那就自己新建一个。
babelrc配置完之后,把项目跑起来发现并不起作用,组件样式并没有加上。
这里其实错的不是我们,也不是antd,而是这个脚手架它默认是不使用.babelrc的,它使用的是package.json中的babel配置和内部配置。
所以我们要将脚手架的内部配置项暴露出来进行修改,使用 npm run eject这个命令来暴露配置,运行npm run eject之后,项目根目录会生成config文件夹。
找到config/webpack.config.js文件,将babelrc:false改为true,意思是启用.babelrc的配置:
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
// @remove-on-eject-begin
babelrc: false,
configFile: false,
presets: [require.resolve('babel-preset-react-app')],
// Make sure we have a unique cache identifier, erring on the
// side of caution.
// We remove this when the user ejects because the default
// is sane and uses Babel options. Instead of options, we use
// the react-scripts and babel-preset-react-app versions.
cacheIdentifier: getCacheIdentifier(
isEnvProduction
? 'production'
: isEnvDevelopment && 'development',
[
'babel-plugin-named-asset-import',
'babel-preset-react-app',
'react-dev-utils',
'react-scripts',
]
),
// @remove-on-eject-end
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,
},
}
还没有完,此时如果运行项目,浏览器还会报错,为什么会报错呢?因为上面一步开启了使用.babelrc文件,但是.babelrc的配置不正确,我们需要修改(为什么不正确呢?因为creat-react-app有一些默认的babel配置放到了package.json中)
此时将package.json中的babel下面的 “presets”: [ “react-app” ] 配置到 .babelrc中,并将package.json中的babel删除掉,如图:
总结一下,create-react-app的脚手架使用anted的css按需加载,由于此脚手架默认不支持使用.babelrc文件,所以需要将其配置暴露出来,需要用到npm run eject 命令,暴露配置文件后需要在config/webpack.config.js中开启使用.babelrc文件的功能,开启后配置.babelrc。配置的时候需要注意一点,将package.json中的babel配置剪贴到.babelrc中。