webpack3.x升级到webpack4.x
虽然说webpack5都已经出了,但是,可能有一部分人还在用webpack3,因此这篇文章主要是基于vue-cli中到项目配置,从webpack3升级到4.x。
由于webpack3升级到4以后,很多配置项发生了变化,因此在升级过程中会遇到很多坑。
- webpack.base.conf.js
首先。从webpack.base.conf.js开始,输入输出和上下文配置基本一样的,这边在plugin的位置引入了VueLoaderPlugin,同时把HtmlWebpackPlugin也提取到这里
plugins: [
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
filename: `index.html`,
template: root + '/index.html',
// favicon:path.resolve('favicon.ico'),
prod: true,
hash: true,
minify: {
removeAttributeQuotes: true,
collapseWhitespace: true,
html5: true,
minifyCSS: true,
removeComments: true,
removeEmptyAttributes: true
}
}),
]
- webpack.dev.conf.js
webpack4必须引入一个mode参数左右判断dev和prod的环境,
基本的一些配置信息还是相同的,下图左侧位webpack3的配置,右侧是webpack4的配置。
- webpack.prod.conf.js(重点在这个文件)
1)webpack4取消了uglify-webpack-plugin这个插件,改用了minizer这个属性
optimization: {
noEmitOnErrors: true,
minimizer: [
// new UglifyJsPlugin({
// cache: true,
// parallel: true,
// sourceMap: false // set to true if you want JS source maps
// }),
new OptimizeCssAssetsPlugin({
cssProcessor: require('cssnano')
})
],
splitChunks: {
chunks: 'all'
}
},
2)extract-text-webpack-plugin,CommonsChunksPlugin这个插件也不再适用
3)引入了happpyPack并行打包
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const merge = require('webpack-merge');
const utils = require('./utils')
const path = require('path')
const webpackbase = require('./webpack.base.conf.js');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const chalk = require('chalk');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const config = require('../config');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
const _version = new Date().getTime();
const HtmlWebpackTagsPlugin = require('html-webpack-tags-plugin');
const dllHelper = require('../config/dllHelper');
const CopyWebpackPlugin = require('copy-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const HappyPack = require('happypack');
const webpackProdConfig = {
devtool: 'inline-cheap-source-map',
mode: 'production',
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: './'
},
optimization: {
noEmitOnErrors: true,
minimizer: [
// new UglifyJsPlugin({
// cache: true,
// parallel: true,
// sourceMap: false // set to true if you want JS source maps
// }),
new OptimizeCssAssetsPlugin({
cssProcessor: require('cssnano')
})
],
splitChunks: {
chunks: 'all'
}
},
plugins: [
new CleanWebpackPlugin(),
// new ExtractTextPlugin({
// filename: utils.assetsPath('css/[name].[contenthash].css'),
// allChunks: true,
// }),
new OptimizeCSSPlugin({
cssProcessorOptions: true
? { safe: true, map: { inline: false } }
: { safe: true }
}),
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: 'static',
ignore: ['.*']
}
]),
...dllHelper.genDllReferences(),
new HappyPack({
id: 'js',
use: [
{
test: /\.js$/,
loader: 'babel-loader',
},
]
}),
new HtmlWebpackTagsPlugin({
assets: dllHelper.loadDllAssets(),
append: false
}),
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
// favicon:path.resolve('favicon.ico'),
prod: true,
hash: true,
minify: {
removeAttributeQuotes: true,
collapseWhitespace: true,
html5: true,
minifyCSS: true,
removeComments: true,
removeEmptyAttributes: true
}
}),
new MiniCssExtractPlugin({
filename: utils.assetsPath(`css/[name].${_version}.css`),
chunkFilename: utils.assetsPath(`css/[name].${_version}.css`),
}),
new ProgressBarPlugin(
{
format: chalk.blueBright(' build :bar :percent (:elapsed seconds) '),
clear: false,
summary: false,
customSummary: res => {
process.stderr.write(chalk.blueBright.bold(` build end use time ${res} \n`))
}
}
),
// new ParallelUglifyPlugin({
// uglifyJS: {
// output: {
// beautify: false,
// comments: false
// },
// compress: {
// drop_console: true,
// collapse_vars: true,
// reduce_vars: true
// }
// }
// })
]
}
// if (config.build.productionGzip) {
// const CompressionWebpackPlugin = require('compression-webpack-plugin')
// webpackProdConfig.plugins.push(
// new CompressionWebpackPlugin({
// filename: '[path].gz[query]',
// algorithm: 'gzip',
// test: new RegExp(
// '\\.(' +
// config.build.productionGzipExtensions.join('|') +
// ')$'
// ),
// threshold: 10240,
// minRatio: 0.8
// })
// )
// }
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackProdConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = merge(webpackbase, webpackProdConfig)
4)引入了webpack.dll.conf.js用于提升打包速度
const path = require('path')
const webpack = require('webpack');
const merge = require('webpack-merge')
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const {CleanWebpackPlugin} = require("clean-webpack-plugin")
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const utils = require('./utils')
const dllConfig = {
mode: 'production',
context: path.resolve(__dirname, '../'),
output: {
path: path.join(__dirname, '../static/lib'),
filename: '[name]_[hash:4].dll.js',
library: '[name]_[hash:4]'
},
entry: {
lib: [
'axios',
'moment',
],
vue: [
'vue/dist/vue.js',
'vue-router',
],
},
// optimization: {
// noEmitOnErrors: true,
// minimizer: [
// new OptimizeCssAssetsPlugin({
// cssProcessor: require('cssnano')
// })
// ],
// splitChunks: {
// chunks: 'all'
// }
// },
module: {
rules: [{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff",
options: {
name: utils.assetsPath('fonts/[name].[ext]')
}
}, {
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader",
options: {
name: utils.assetsPath('fonts/[name].[ext]')
}
}]
},
plugins: [
new CleanWebpackPlugin(),
new webpack.DllPlugin({
context: __dirname,
path: path.join(__dirname, '../static/dll', '[name].manifest.json'),
name: '_dll_[name]_[hash]',
}),
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
}),
new ExtractTextPlugin('[name].css'),
],
performance: {
hints: "warning", // 枚举
maxAssetSize: 30000000, // 整数类型(以字节为单位)
maxEntrypointSize: 50000000, // 整数类型(以字节为单位)
assetFilter: function(assetFilename) {
// 提供资源文件名的断言函数
return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
}
}
}
module.exports = merge(dllConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: true,
extract: true,
usePostCSS: true
})
}
});
小结:详细的工程参考下面github地址
文章写的比较简介,最好自己从头到尾配置一遍,这样印象比较深刻
https://github.com/michael8512/vue2x-webpack4
还没有评论,来说两句吧...