前言
对于大中型前端项目为了解耦与复用,更多的公司会选择自己封装组件库,那么一次引入整个组件库必然导致项目过大,如何按需加载则必须要做,antd团队给我提供了babel-plugin-import这个模块,可以很好的解决这个问题,在学习react的过程中,正好需要用到这个antd组件库,于是正好研究了一下
按需加载
如果想使用按需加载功能,我们可以通过babelrc文件更改或者通过babel-loader,我选择了通过babel-loader这种方式进行更改,使用yarn eject对内置的webpack进行释放,接在找到babel-loader,添加以下代码
{
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', style: true }], // 添加的代码
],
style: true can reduce the bundle size significantly, depending on your usage of the library.
定制主题
有时候我们想对主题进行更改,这时候就需要对less-loader的options属性做一些更改,因为antd的样式是使用less写的,代码如下
if (preProcessor) {
let loader = {
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
if (preProcessor === 'less-loader') {
loader.options.lessOptions = {
/* modifyVars: {
'primary-color': '#1DA57A',
'link-color': '#1DA57A',
'border-radius-base': '2px',
}, */
javascriptEnabled: true,
}
}
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
loader
)
}
return loaders
Note:上面这段代码是在原有的内置webpack配置中直接进行修改之后得到的