1.安装
npm i compression-webpack-plugin@6.1.0
//最新版8.x打包报错TypeError: Cannot read property 'tapPromise' of undefined
npm install @gfx/zopfli --save-dev //压缩率比gzip高,注意brotli压缩只有https才能支持
npm i svg-sprite-loader image-webpack-loader -D
2.具体配置
const path = require("path");
// 在vue-config.js 中加入
// 开启gzip压缩
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const zlib = require("zlib");
// 判断开发环境
const isProduction = process.env.NODE_ENV === "production";
/*文件路劲*/
const resolve = (dir) => {
return path.join(__dirname, dir);
};
module.exports = {
//webpack配置
configureWebpack: (config) => {
// 开启gzip压缩
if (isProduction) {
config.plugins.push(
new CompressionWebpackPlugin({
filename: "[path][base].gz",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8,
deleteOriginalAssets: true
}),
//或者
new CompressionWebpackPlugin({
filename: "[path][base].br",
algorithm: "brotliCompress",
test: /\.(js|css|html|svg)$/,
compressionOptions: {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 11,
},
},
threshold: 10240,
minRatio: 0.8,
}),
);
// 取消webpack警告的性能提示
config.performance = {
hints: "warning",
//入口起点的最大体积
maxEntrypointSize: 50000000,
//生成文件的最大体积
maxAssetSize: 30000000,
//只给出 js 文件的性能提示
assetFilter: function(assetFilename) {
return assetFilename.endsWith(".js");
},
};
}
},
// 基本路径
publicPath: "./", // 可以设置成相对路径,这样所有的资源都会被链接为相对路径,打出来的包可以被部署在任意路径
//outputDir: "dist", //打包时生成的生产环境构建文件的目录
//assetsDir: "public", // 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录
devServer: {
disableHostCheck: true,
overlay: { // 让浏览器 overlay 同时显示警告和错误
warnings: true,
errors: true
},
host: "localhost",
port: 8080, // 端口号
https: false, // https:{type:Boolean}
open: false, //配置后自动启动浏览器
hotOnly: true, // 热更新
proxy: {
"/api": {
target: "http://197.0.0.1:8080", //API服务器的地址
changeOrigin: true,
ws: true,//websocket支持
secure: false,
pathRewrite: {
"^/api": "",
},
},
},
},
// 如果你不需要使用eslint,把lintOnSave设为false即可
lintOnSave: false,
chainWebpack: (config) => {
// 开启分离js
chunks: 'all';
cacheGroups: {
vendors: {
name: 'chunk-vendors';
test: /[\\/]node_modules[\\/]/;
chunks: 'initial';
priority: 2;
reuseExistingChunk: true;
enforce: true
};
core: {
name: 'chunk-vendors-core';
test: /[\\/]node_modules[\\/]core-js[\\/]/;
chunks: 'initial';
priority: 2;
reuseExistingChunk: true;
enforce: true
}
};
config.module.rule("svg").exclude.add(resolve("src/icons")).end();
config.module
.rule("icons")
.test(/\.svg$/)
.include.add(resolve("src/icons"))
.end()
.use("svg-sprite-loader")
.loader("svg-sprite-loader")
.options({
symbolId: "icon-[name]",
});
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
bypassOnDebug: true
})
.end();
config.resolve.alias
.set("@", resolve("src")) // key,value自行定义,比如.set('@@', resolve('src/components'))
.set("@c", resolve("src/components"))
.set("_api", resolve("src/api"));
},
// 打包时不生成.map文件
productionSourceMap: false,
};