webpack3升级webpack4
为了优化包体积大小,想要将老项目的webpack3升级到webpack4,再升级到webpack5
一、升级版本
1、webpack ^3.1.0 => ^4.29.6
2、webpack-cli ^3.1.2 => ^3.3.0
3、webpack-dev-server ^2.11.3 => ^3.2.1
4、html-webpack-plugin ^2.30.1 => ^3.2.0
5、vue-loader ^13.3.0 => ^15.7.0 (不升级,会报找不到vue模块,下有详细说明)
6、替换extract-text-webpack-plugin为mini-css-extract-plugin ^0.5.0,下有详细说明
二、跑通本地npm run dev
1、如果按照上述操作,升级之后,执行npm run dev,会碰到一个问题
这是由于vue-loader升级到^15之后,需要配置VueLoaderPlugin,在webpack.base.conf.js里加入代码
const { VueLoaderPlugin } = require('vue-loader'); // 新增 在plugins: [ new VueLoaderPlugin(), // 新增 ]
三、跑通npm run build
1、extract-text-webpack-plugin替换成mini-css-extract-plugin
webpack4不支持extract-text-webpack-plugin,因此替换为mini-css-extract-plugin
配置方式:webpack.prod.conf.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module: { rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', ] }, { test: /\.styl(us)?$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'stylus-loader' ] }, { test: /\.less$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'less-loader' ] }, { test: /\.(scss|sass)$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader' ] }, ] }, plugins: [ new MiniCssExtractPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css'), }), // 新增 ]
2、去掉new webpack.optimize.CommonsChunkPlugin
webpack4不再支持CommonsChunkPlugin,需要改成以下形式
optimization: { splitChunks: { chunks: 'async', minSize: 20000, minChunks: 1, maxAsyncRequests: 30, maxInitialRequests: 30, cacheGroups: { vendors: { // 工程基础包 例如包括vue、vue-router、axios等常用不改变的包,可以做缓存 test: /[\\/]node_modules[\\/]/, name: 'vendor', chunks: 'all', priority: -10, reuseExistingChunk: true, }, app: { // 业务基础包大部分不是node_modules的模块,例如我们在common中存放的一些基础组件,其次是一些三方的组件库(这些是在node_modules中的,但是因为经常变动所以不适宜放在vendor中) minChunks: 3, name: 'app', priority: -20, reuseExistingChunk: true, }, } } },
升级过程遇到的其他的坑
https://segmentfault.com/a/1190000021284090?utm_source=tag-newest
转载:https://blog.csdn.net/litCabbage/article/details/117959964