对antd这个庞然大物的优化,主要靠babel-plugin-import。
npm: www.npmjs.com/package/bab…
倒不是有多难,而是这个过程坑太多。
根据官网介绍,babelrc和babel-loader作为配置节点都OK,那么我选babel-loader。
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react'],
plugins: [
'@babel/plugin-transform-runtime',
['import', {
libraryName: 'antd',
libraryDirectory: 'es', // 这条加了可以再少20k左右
style: true, // 也可以配置为'css'。配置true可以减少30k
}]
],
}
}
}
上面配置是几经调较之后的最终形态,用了Button/Menu/Layout这3个组件,antd独立chunk为451k。
然后说说几个大坑。
报错1:缺少less支持
我不会less,也不打算用,所以没配置在webpack里。但这个坑是第一个掉进去的。
ERROR in ./node_modules/antd/es/layout/style/index.less 1:0
Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
好吧,随手装一个less-loader,配置:
{
test: /\.less$/i,
use: [
{
loader: 'less-loader',
}
],
}
继续报错:
报错2: less-loader的版本
ERROR in ./node_modules/antd/es/button/style/index.less
Module build failed (from ./node_modules/less-loader/dist/cjs.js):
TypeError: this.getOptions is not a function
这个问题是less-loader版本太高造成的。默认安装的是less-loader@^8,是给webpack5用的。那么给我这webpack4降到v7试试。
$ npm i -D less-loader@^7
$ npm run build
继续报错:
报错3:javascriptEnabled
Inline JavaScript is not enabled. Is it set in your options?
那么这个javascriptEnabled项,看上面报错的字面意思,应当是配置为:
{
test: /\.less$/i,
use: [
{
loader: 'less-loader',
options: {
javascriptEnabled: true // 这么写是错的
},
}
]
}
实际上应该是lessOption里的配置:
{
test: /\.less$/i,
use: [
{
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true,
}
}
}
]
}
继续报错
报错4:需要样式处理的完整流水线
ERROR in ./node_modules/antd/es/button/style/index.less 5:0
Module parse failed: Unexpected token (5:0)
File was processed with these loaders:
* ./node_modules/less-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
也就是说我还得用其他的loader才能行呗?流水线铺满:
{
test: /\.less$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true
}
}
}
]
}
可以了
Antd的番外坑
最初为了研究webpack,新建了一个demo项目,项目中根据antd的官方指导,在app.css中,使用了全量css引用:
@import "~antd/dist/antd.css"
导致打包过程中一直带着全量的css代码,包体积一直下不来。
问题是后来忘了有这么回事,几乎抓狂。
但是如果不借助babel-plugin-import打包,这行import是不能去掉的,否则页面没有样式。
以上。