背景
在 vue-cli3
发布之前,使用 vue-cli2
构建的 vue
项目是基于 webpack3.x
的,伴随着项目的版本迭代,功能逐渐增多,文件也逐渐增多,打包时间从最初的 5
分钟,最久的时候 19
分半钟。
因为使用 ts
的缘故,每次打包 ts-loader
需要进行类型检查,导致耗时剧增。权衡利弊下,将 ts-loader
的类型检查禁用后(transpileOnly
选项设置为 true
),打包时间锐减到 2
分半钟。
随着时间的推移,项目进一步迭代,打包时间再次高涨到 9
分钟,恰逢 webpack4
对于打包性能的提升,于是就有了这篇升级日志:
起步
整体思路:
- 升级项目依赖
- 跑通开发环境打包
- 跑通生成环境打包
升级项目依赖
一开始的项目依赖升级的思路是,先升级 webpack
到最新的版本,然后逐步升级 loader
、plugin
、babel
等依赖。但是基于之前其他项目升级 webpack4
的过程,发现逐步升级会耗费一部分时间在新旧依赖的问题上,于是决定激进一点,使用 ncu
一次性将 package.json
中包含的项目依赖升级到最新版本(部分依赖可以不升级)。
# 安装 ncu
npm i -g ncu
# 检查项目依赖的版本与最新版本,列出清单
ncu
# 将 `package.json` 中包含的依赖的版本号,更新到最新
ncu -u
# 删除旧的依赖,安装新的依赖
rm -rf node_modules
rm package-lock.json
npm i
跑通开发环境打包
npm run dev
运行过程中遇到的问题:
-
vue-loader was used without the corresponding plugin.
报错日志:
ERROR in ./src/App.vue Module Error (from ./node_modules/vue-loader/lib/index.js): vue-loader was used without the corresponding plugin. Make sure to include VueLoaderPlugin in your webpack config. @ ./src/main.ts 2:0-28 45:23-26 @ multi ./build/dev-client ./src/main.ts
ERROR in ./src/page/supplier/preferential/full-discount/view.vue?vue&type=script&lang=ts& Module not found: Error: Can't resolve '../../../../interface/coupon.coupon_code_view' in '/Users/yourProjectPath/src/page/supplier/preferential/full-discount' @ ./src/page/supplier/preferential/full-discount/view.vue?vue&type=script&lang=ts& 19:0-70 @ ./src/page/supplier/preferential/full-discount/view.vue @ ./src/router/supplier/preferential.ts @ ./src/router/supplier/index.ts @ ./src/router/index.ts @ ./src/main.ts @ multi ./build/dev-client ./src/main.ts
原因:
vue-loader
升级到v15.x
以后,需要搭配VueLoaderPlugin
使用如何解决:
// webpack.base.confg.js const { VueLoaderPlugin } = require('vue-loader'); module.exports = { // ... plugins: [ new VueLoaderPlugin() ] }
-
Component template requires a root element, rather than just text.
Module Error (from ./node_modules/vue-loader/lib/loaders/templateLoader.js): (Emitted value instead of an instance of Error) Errors compiling template: Component template requires a root element, rather than just text. 1 | | 2 | #app | ^^^^ 3 | router-view | ^^^^^^^^^^^^^
@ ./src/App.vue?vue&type=template&id=7ba5bd90&lang=pug& 1:0-238 1:0-238
@ ./src/App.vue
@ ./src/main.ts
@ multi ./build/dev-client ./src/main.ts
```
```log
Module Error (from ./node_modules/vue-loader/lib/loaders/templateLoader.js):
(Emitted value instead of an instance of Error)
Errors compiling template:
text "div
el-card" outside root element will be ignored.
```
**原因:**
引用自 `vue-loader` 文档:
> 注意有些模板的 loader 会导出一个编译好的模板函数而不是普通的 HTML,诸如 pug-loader。为了向 Vue 的模板编译器传递正确的内容,你必须换用一个输出普通 HTML 的 loader。例如,为了支持 ``,你可以使用 pug-plain-loader:
**如何解决**
```js
{
module: {
rules: [
{
test: /\.pug$/,
loader: 'pug-plain-loader'
}
]
}
}
```
-
Cannot find module '@babel/core'
报错日志:
ERROR in ./src/store/mutation/util.js Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Cannot find module '@babel/core' babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'. at Function.Module._resolveFilename (module.js:538:15) at Function.Module._load (module.js:468:25) at Module.require (module.js:587:17) at require (internal/module.js:11:18) at Object.
(/Users/yourProjectPath/node_modules/babel-loader/lib/index.js:10:11) at Module._compile (module.js:643:30) at Object.Module._extensions..js (module.js:654:10) at Module.load (module.js:556:32) at tryModuleLoad (module.js:499:12) at Function.Module._load (module.js:491:3) at Module.require (module.js:587:17) at require (internal/module.js:11:18) at loadLoader (/Users/yourProjectPath/node_modules/loader-runner/lib/loadLoader.js:18:17) at iteratePitchingLoaders (/Users/yourProjectPath/node_modules/loader-runner/lib/LoaderRunner.js:169:2) at runLoaders (/Users/yourProjectPath/node_modules/loader-runner/lib/LoaderRunner.js:365:2) at NormalModule.doBuild (/Users/yourProjectPath/node_modules/webpack/lib/NormalModule.js:295:3) @ ./src/store/mutation/nav.ts 3:0-48 54:41-63 59:41-63 63:41-63 70:37-59 @ ./src/store/mutation/index.ts @ ./src/store/index.ts @ ./src/main.ts @ multi ./build/dev-client ./src/main.ts 原因:
根据错误提示可以知道,
babel-loader@8
依赖Babel 7.x
(也就是@babel/core
),于是选择卸载babel-core
,安装@babel/core
。如何解决:
npm un babel-core npm i @babel/core
-
ValidationError: Invalid options object. CSS Loader has been initialised using an options object that does not match the API schema.
ERROR in ./node_modules/element-ui/lib/theme-chalk/index.css (./node_modules/css-loader/dist/cjs.js??ref--11-1!./node_modules/element-ui/lib/theme-chalk/index.css) Module build failed (from ./node_modules/css-loader/dist/cjs.js): ValidationError: Invalid options object. CSS Loader has been initialised using an options object that does not match the API schema.
object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals? }
at validate (/Users/yourProjectPath/node_modules/css-loader/node_modules/schema-utils/dist/validate.js:50:11)
at Object.loader (/Users/yourProjectPath/node_modules/css-loader/dist/index.js:34:28)
@ ./node_modules/element-ui/lib/theme-chalk/index.css 4:14-81 14:3-18:5 15:22-89
@ ./src/main.ts
@ multi ./build/dev-client ./src/main.ts
```
**原因:**
`minimize` 配置项被移除导致
**如何解决:**
删除 `css-loader` 的 `minimize` 选项
-
You may need an additional loader to handle the result of these loaders.
ERROR in ./src/page/supplier/stock/storage/edit.vue?vue&type=template&id=62f3141a&lang=pug& 2:4 Module parse failed: Assigning to rvalue (2:4) File was processed with these loaders: * ./node_modules/vue-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|
> div(v-loading="bIsPageLoading")
| el-card
| el-form(ref="form" label-width="120px" :model="oForm" :rules="oRules")
@ ./src/page/supplier/stock/storage/edit.vue 1:0-92 11:2-8 12:2-17 31:4-36:6 31:76-36:5 33:16-22 34:25-40
@ ./src/router/supplier/stock.ts
@ ./src/router/supplier/index.ts
@ ./src/router/index.ts
@ ./src/main.ts
@ multi ./build/dev-client ./src/main.ts
```
-
The 'mode' option has not been set
WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment. You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/
原因:
webpack4
开始,提供了mode
选项用来启用webpack
提供的内置选项,没有设置时,默认值为production
如何解决:
开发环境设置:
development
,生成环境设置:production
至此已经可以跑通开发环境打包了
跑通生成环境打包
运行过程中遇到的问题:
-
webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead.
/Users/yourProjectPath/node_modules/webpack/lib/webpack.js:189 throw new RemovedPluginError(errorMessage); ^ Error: webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead. at Object.get [as CommonsChunkPlugin] (/Users/yourProjectPath/node_modules/webpack/lib/webpack.js:189:10) at Object.
(/Users/yourProjectPath/build/webpack.prod.conf.js:85:26) at Module._compile (module.js:643:30) at Object.Module._extensions..js (module.js:654:10) at Module.load (module.js:556:32) at tryModuleLoad (module.js:499:12) at Function.Module._load (module.js:491:3) at Module.require (module.js:587:17) at require (internal/module.js:11:18) at Object. (/Users/yourProjectPath/build/build.js:12:23) at Module._compile (module.js:643:30) at Object.Module._extensions..js (module.js:654:10) at Module.load (module.js:556:32) at tryModuleLoad (module.js:499:12) at Function.Module._load (module.js:491:3) at Function.Module.runMain (module.js:684:10) 原因:
https://webpack.js.org/migrat...
根据错误提示信息可以知道,
webpack4
开始CommonsChunkPlugin
被删除如何解决:
将
CommonsChunkPlugin
相关的配置删除,改用optimization.splitChunks
配置项The default configuration was chosen to fit web performance best practices, but the optimal strategy for your project might differ. If you're changing the configuration, you should measure the impact of your changes to ensure there's a real benefit.
https://webpack.js.org/plugin...根据插件文档的描述,这里我们没有额外增加配置,使用的是
optimization.splitChunks
配置项的默认值。// webpack.config.js module.exports = { // ... optimization: { splitChunks: { chunks: 'async', minSize: 30000, maxSize: 0, minChunks: 1, maxAsyncRequests: 5, maxInitialRequests: 3, automaticNameDelimiter: '~', automaticNameMaxLength: 30, name: true, cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/, priority: -10 }, default: { minChunks: 2, priority: -20, reuseExistingChunk: true } } } } };
-
Error: Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead
/Users/yourProjectPath/node_modules/webpack/lib/Chunk.js:866 throw new Error( ^ Error: Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead at Chunk.get (/Users/yourProjectPath/node_modules/webpack/lib/Chunk.js:866:9) at /Users/yourProjectPath/node_modules/extract-text-webpack-plugin/dist/index.js:176:48 at Array.forEach (
) at /Users/yourProjectPath/node_modules/extract-text-webpack-plugin/dist/index.js:171:18 at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/yourProjectPath/node_modules/tapable/lib/HookCodeFactory.js:33:10), :7:1) at AsyncSeriesHook.lazyCompileHook (/Users/yourProjectPath/node_modules/tapable/lib/Hook.js:154:20) at Compilation.seal (/Users/yourProjectPath/node_modules/webpack/lib/Compilation.js:1342:27) at compilation.finish.err (/Users/yourProjectPath/node_modules/webpack/lib/Compiler.js:675:18) at hooks.finishModules.callAsync.err (/Users/yourProjectPath/node_modules/webpack/lib/Compilation.js:1261:4) at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/yourProjectPath/node_modules/tapable/lib/HookCodeFactory.js:33:10), :24:1) at AsyncSeriesHook.lazyCompileHook (/Users/yourProjectPath/node_modules/tapable/lib/Hook.js:154:20) at Compilation.finish (/Users/yourProjectPath/node_modules/webpack/lib/Compilation.js:1253:28) at hooks.make.callAsync.err (/Users/yourProjectPath/node_modules/webpack/lib/Compiler.js:672:17) at _done (eval at create (/Users/yourProjectPath/node_modules/tapable/lib/HookCodeFactory.js:33:10), :9:1) at _err1 (eval at create (/Users/yourProjectPath/node_modules/tapable/lib/HookCodeFactory.js:33:10), :32:22) at _addModuleChain (/Users/yourProjectPath/node_modules/webpack/lib/Compilation.js:1185:12) 原因:
extract-text-webpack-plugin 在
webpack4
的时候被废弃,改用mini-css-extract-plugin如何解决:
将
extract-text-webpack-plugin
相关的配置删除,改用mini-css-extract-plugin
详情见插件文档:https://webpack.js.org/plugin...
// webpack.config.js const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { plugins: [ new MiniCssExtractPlugin({ filename: 'css/[name].[contenthash].css' }), ], module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { hmr: process.env.NODE_ENV === 'development', }, }, 'css-loader', ], }, ], }, };
-
Unexpected token: keyword «const»
ERROR in static/js/app.2c7ff4a31971e22c9397.js from UglifyJs Unexpected token: keyword «const» [static/js/app.2c7ff4a31971e22c9397.js:3865,0]
原因:
uglifyjs-webpack-plugin
不支持es6
语法如何解决:
将
uglifyjs-webpack-plugin
相关的配置删除,不用额外增加配置,因为production
模式下,webpack
使用terser-webpack-plugin
来最小化JavaScript
文件
至此生产环境打包已经可以跑通了