webpack 4 出來也已經一年了,公司的老專案用的還是webpack3,也是時候該升級一波了。說實話webpack4還是有幾點挺吸引我的,估計也是感受到了parcel的壓力,4這個版本內建了很多預設配置。
遷移的坑
- CommonsChunkPlugin 廢除, webpack 4內建了optimization.splitChunks 和 runtimeChunk 進行程式碼拆分
- ExtractTextPlugin 不支援webpack4,官方推薦了一個MiniCssExtractPlugin來拆分chunk中的css程式碼
- vue-loader 的升級,vue-loader 版本由14 升級到了15, 之前的配置也改變了具體參考從 v14 遷移
基礎配置
const package = require('../package.json');
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const utils = require('./utils');
function resolve (dir) {
return path.join(__dirname, dir);
}
module.exports = {
entry: {
main: '@/main',
'vender-exten': '@/vendors/vendors.exten.js'
},
output: {
path: path.resolve(__dirname, '../dist/' + package.version) // 輸出檔案的絕對路徑
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
exclude: /node_modules/,
options: {
emitError: true,
emitWarning: false,
failOnError: true
}
},
{
test: /\.vue$/,
exclude: /node_modules/,
loader: 'vue-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.js[x]?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
}
]
},
plugins: [
new VueLoaderPlugin(),
],
resolve: {
extensions: ['.js', '.vue'],
alias: {
'@': resolve('../src')
}
},
externals: {
AMap: 'AMap',
vue: 'Vue',
iview: 'iview',
'vue-router': 'VueRouter',
vuex: 'Vuex'
}
};
複製程式碼
如上,實現了對vue,jsx, js, 和資原始檔對處理和轉譯
開發環境配置
const HtmlWebpackPlugin = require("html-webpack-plugin");
const merge = require("webpack-merge");
const webpackBaseConfig = require("./webpack.base.config.js");
const config = require("./config");
const webpack = require("webpack");
module.exports = merge(webpackBaseConfig, {
mode: 'development',
devtool: '#source-map',
output: {
publicPath: '/dist/',
filename: '[name].js',
chunkFilename: '[name].chunk.js'
},
plugins: [
new HtmlWebpackPlugin({
title: 'admin management',
filename: '../index.html',
inject: false
}),
],
module: {
rules: [
{
test: /\.css$/,
use: ['vue-style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.less$/,
use: [
'vue-style-loader',
'css-loader',
'postcss-loader',
'less-loader'
]
}
]
},
//設定跨域代理
devServer: {
public: 'local.xxxx.net:9000',
port: 9000,
proxy: {
'/login': {
target: config.devApi.passport,
pathRewrite: { '^/login': '/login' },
changeOrigin: true
},
'/v3': {
target: config.devApi.sass,
pathRewrite: { '^/v3': '/v3' },
changeOrigin: true
}
}
}
});
複製程式碼
如上,配置了開發環境的配置,注意webpack4多了一個model,model有三個選項可以選擇:development, production, 和none,
可以看官方的這個圖,webpack會根據model自動開啟內建外掛生產環境配置
const HtmlWebpackPlugin = require('html-webpack-plugin')
const TerserJSPlugin = require('terser-webpack-plugin');
const webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const cleanWebpackPlugin = require('clean-webpack-plugin')
const merge = require('webpack-merge')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const webpackBaseConfig = require('./webpack.base.config.js')
const path = require('path')
const package = require('../package.json')
module.exports = merge(webpackBaseConfig, {
model: 'production',
output: {
publicPath: '/' + package.version + '/', // 所有引入的檔案資源都加上publicPath路徑
filename: '[name].[contenthash].js', // 輸出 bundle 的名稱, 入口(non-entry)
chunkFilename: '[name].[contenthash].chunk.js' // 非入口(non-entry) chunk 檔案的名稱
},
optimization: {
splitChunks: {
cacheGroups: {
// 快取組
commons: {
test: /[\\/]node_modules[\\/]/, // 只抽取引入的node_modules檔案
name: 'vender-exten', // 要快取的 分隔出來的 chunk 名稱
chunks: 'all' // 對所有的chunk都進行快取
}
}
},
runtimeChunk: {
name: 'runtime'
},
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})]
},
module: {
rules: [
{
test: /\.css?$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader'
]
},
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'less-loader'
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
chunkFilename: '[name].[contenthash].css'
}),
new cleanWebpackPlugin(['dist/*'], {
root: path.resolve(__dirname, '../')
}),
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: '../static',
ignore: ['.*']
}
]),
new HtmlWebpackPlugin({
title: 'admin',
favicon: './static/favicon.ico',
filename: '../index.html',
template: '!!ejs-loader!./src/template/index.ejs',
inject: false
})
]
});
複製程式碼
生產環境
1.使用MiniCssExtractPlugin,來拆分css,我可以可以options裡面有兩個值filename和chunkFilename, filename指的是entry中key生成的css名稱, chunkFilename是webpack中每個chunk拆分生成css的名稱。
2.使用OptimizeCSSAssetsPlugin 對打包之後的css檔案進行壓縮,
3.使用splitChunks對公共程式碼進行抽取快取,我們先來看一下這個外掛的預設配置
module.exports = {
optimization: {
splitChunks: {
chunks: 'async', "initial" | "all"(推薦) | "async" (預設就是async)
minSize: 30000, 最小尺寸,30000
maxSize: 0, 最小尺寸
minChunks: 1, 最小 chunk ,預設1
maxAsyncRequests: 5, // 最大非同步請求數, 預設5
maxInitialRequests: 3, // 最大初始化請求書,預設3
automaticNameDelimiter: '~', // 打包分隔符
name: true,
cacheGroups: { // 重點,快取配置
vendors: {
test: /[\\/]node_modules[\\/]/, // 只快取node_modules裡面的模組
priority: -10 // // 快取組優先順序,可能有多個
},
}
}
}
};
複製程式碼
看下我的配置
splitChunks: {
cacheGroups: {
// 快取組
commons: {
test: /[\\/]node_modules[\\/]/, // 只抽取引入的node_modules檔案
name: 'vender-exten', // 要快取的 分隔出來的 chunk 名稱
chunks: 'all' // 對所有的chunk都進行快取
}
}
}
複製程式碼
通過webpack-bundle-analyzer生成的視覺化圖示分析檢視專案中的多個chunk共同引入的lib包
抽離5個依賴的lib包,進行快取4.使用optimization.runtimeChunk,去快取生成chunk過程中生成的webpack公用程式碼
5.使用TerserJSPlugin對js進行壓縮