webpack 优化相关
1. dll 动态链库配置
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./vendor-manifest.json'),
})
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
vendor: ['vue/dist/vue.esm.js', 'vuex', 'axios', 'vue-router'],
},
output: {
path: path.join(__dirname, './public/static/js'),
filename: '[name].dll.js',
library: '[name]_library',
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, '.', '[name]-manifest.json'),
name: '[name]_library',
context: __dirname,
}),
],
};
<script src="<%= BASE_URL %>static/js/vendor.dll.js"></script>
2. 模块懒加载
const Home = () => import(/* webpackChunkName: "home" */ './index.vue')
3. 配置别名
config.resolve.alias
.set('@store', resolve('src/store'))
.set('@components', resolve('src/components'))
.set('@assets', resolve('src/assets'))
.set('@utils', resolve('src/utils'));
4. 去除 console.log
new TerserPlugin({
terserOptions: {
ecma: undefined,
warnings: true,
parse: {},
compress: {
drop_console: false,
drop_debugger: false,
pure_funcs: ['console.log'],
},
},
}),
5. 添加版本部署信息
function getGitVersionInfo() {
try {
const exec = require("child_process").execSync;
const branchName = exec("git branch")
.toString()
.match(/\*\s+(.+)/)[1];
const commitHash = exec("git log")
.toString()
.match(/^commit\s+(.+)/)[1]
.slice(0, 8);
return { branchName, commitHash };
} catch (e) {
return { branchName: "unknown", commitHash: "unknown" };
}
}
function getTimeStamp() {
const now = new Date();
const year = now.getFullYear();
const month =
now.getMonth() + 1 > 9 ? now.getMonth() + 1 : `0${now.getMonth() + 1}`;
const date = now.getDate() > 9 ? now.getDate() : `0${now.getDate()}`;
const hour = now.getHours() > 9 ? now.getHours() : `0${now.getHours()}`;
const min = now.getMinutes() > 9 ? now.getMinutes() : `0${now.getMinutes()}`;
const sec = now.getSeconds() > 9 ? now.getSeconds() : `0${now.getSeconds()}`;
return `${year}-${month}-${date} ${hour}:${min}:${sec}`;
}
function genBuildInfo() {
let result = "";
const gitInfo = getGitVersionInfo();
result = `%c ***: ${gitInfo.branchName} -> ${
gitInfo.commitHash
} -> ${getTimeStamp()} `;
return result;
}
process.env.VUE_APP_BUILD_INFO = genBuildInfo();
if (process.env.NODE_ENV !== "development") {
console.warn(
process.env.VUE_APP_BUILD_INFO,
"color: #fff; background-color: #fd6720; border-radius: 4px; padding: 2px 0;"
);
}
6. autoprefixer 自动增加 css3 浏览器前缀
module.exports = {
plugins: {
autoprefixer: {},
},
};
"browserslist": [
"> 1%",
"last 3 versions",
"not ie <= 8",
"chrome >= 14",
"safari >= 3",
"ios >= 8",
"android >= 4.0"
]
7. 忽略第三方包指定目录 IgnorePlugin
config
.plugin("ignore")
.use(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/));
8. happypack 多线程打包
module: {
rules: [
{
test: /\.js$/,
use: 'Happypack/loader?id=js'
},
{
test: /\.css$/,
use: 'Happypack/loader?id=css'
}
]
},
plugins: [
new Happypack({
id: 'js',
use: [
{
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react'
]
}
}
]
}),
new Happypack({
id: 'css',
use: ['style-loader', 'css-loader']
})
]
9. 热更新
const webpack = require('webpack');
module.exports = {
devServer: {
hot: true,
port: 8080,
contentBase: './dist'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin()
]
};
import audio from './audio';
if (module.hot) {
module.hot.accept('./audio.js', (path) => {
console.log(path);
console.log('audio文件更新了');
});
}
10. splitChunks 代码分割
splitChunks: {
chunks: 'async',
minSize: 10000, // 模块的最小体积
minChunks: 1, // 模块的最小被引用次数
maxAsyncRequests: 5, // 按需加载的最大并行请求数
maxInitialRequests: 3, // 一个入口最大并行请求数
automaticNameDelimiter: '~', // 文件名的连接符
name: true,
},
11. 小图片转成base64格式
{
test: /\.(png|jpg|jpeg|gif|svg)$/,
loader: 'url-loader',
options: {
limit: 1024,
name: '[name].[hash:8].[ext]'
}
}
12. css抽成一个, 并增加contentHash
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
mode: "production",
entry: {
index: "./src/index.js",
chunk1: "./src/chunk1.js"
},
output: {
filename: "[name].[chunkhash].js"
},
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader"
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css"
})
]
};