背景:项目之前配置的打包文件太多,体积太大,需要给他进行优化
代码如下:
const webpack = require('webpack')
const time = Date.now()
const path = require('path')
// gzip压缩插件
const CompressionWebpackPlugin = require('compression-webpack-plugin')
// 代码打包之后取出console.log压缩代码
const TerserPlugin = require('terser-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
// 图形化打包详情
const BundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
// const cdn = {
// // 忽略打包的第三方库
// externals: {
// vue: 'Vue',
// vuex: 'Vuex',
// 'vue-router': 'VueRouter',
// axios: 'axios',
// },
// // 通过cdn方式使用
// js: [],
// css: []
// }
function resolve (dir) {
return path.join(__dirname, dir)
}
module.exports = {
// 是否触发eslint检查
lintOnSave: false,
// 基本路径
publicPath: '/',
// 输出文件目录
outputDir: 'dist',
// 放置生成的css和js和img和fonts的目录
// assetsDir: 'ass',
// 存放index.html模板的路径
indexPath: 'index.html',
productionSourceMap: false,
chainWebpack: config => {
// 配置cdn引入
// config.plugin('html').tap(args => {
// args[0].cdn = cdn
// return args
// })
config
.plugin('provide')
.use(webpack.ProvidePlugin, [{
introJs: ['intro.js', 'introJs']
}])
// 移除prefetch插件,避免加载多余的资源
config.plugins.delete('prefetch')
// 定义文件夹的路径
config.resolve.alias
.set('@', resolve('src'))
.set('assets', resolve('src/assets'))
.set('components', resolve('src/components'))
.set('router', resolve('src/router'))
.set('store', resolve('src/store'))
.set('views', resolve('src/views'))
// 压缩图片
const imagesRule = config.module.rule('images')
imagesRule.uses.clear()
imagesRule.use('file-loader')
.loader('url-loader')
.options({
limit: 10240,
fallback: {
loader: 'file-loader',
options: {
outputPath: 'img'
}
}
})
// 压缩响应的app.json返回的代码压缩
config.optimization.minimize(true)
},
// webpack的配置
configureWebpack: config => {
// 忽略打包配置
// config.externals = cdn.externals
// 生产环境配置
if (process.env.NODE_ENV === 'production') {
// 代码压缩去除console.log
config.plugins.push(
new TerserPlugin({
terserOptions: {
ecma: undefined,
warnings: false,
parse: {},
compress: {
drop_console: true,
drop_debugger: false,
pure_funcs: ['console.log'] // 移除console
}
}
})
)
}
// 开启gzip压缩
config.plugins.push(
new CompressionWebpackPlugin(
{
filename: info => {
return `${info.path}.gz${info.query}`
},
algorithm: 'gzip',
threshold: 10240, // 只有大小大于该值的资源会被处理 10240
test: new RegExp('\\.(' + ['js'].join('|') + ')$'
),
minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
deleteOriginalAssets: false // 删除原文件
}
)
)
config.plugins.push(
new OptimizeCSSAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano'),
// cssProcessorOptions: cssnanoOptions,
cssProcessorPluginOptions: {
preset: ['default', {
discardComments: {
removeAll: true,
},
normalizeUnicode: false
}]
},
canPrint: true
})
)
// 展示打包图形化信息
// config.plugins.push(
// new BundleAnalyzer()
// )
// 公共代码抽离
config.optimization = {
splitChunks: {
cacheGroups: {
vendor: {
chunks: 'all',
test: /node_modules/,
name: 'vendor',
minChunks: 1,
maxInitialRequests: 5,
minSize: 0,
priority: 100
},
common: {
chunks: 'all',
test: /[\\/]src[\\/]js[\\/]/,
name: 'common',
minChunks: 2,
maxInitialRequests: 5,
minSize: 0,
priority: 60
},
styles: {
name: 'styles',
test: /\.(sa|sc|c)ss$/,
chunks: 'all',
enforce: true
},
runtimeChunk: {
name: 'manifest'
}
}
}
}
},
css: {
extract: process.env.NODE_ENV === 'development' ? {
ignoreOrder: true,
} : false,
// extract: true,
sourceMap: false,
loaderOptions: {
// 定义全局scss无需引入即可使用
sass: {
data: `@import "~@/assets/scss/variable.scss";`,
data:`@import "~@/assets/scss/mixin.scss";`//全局sass文件
// prependData: `
// @import "@/assets/css/variable.scss";
// @import "@/assets/css/common.scss";
// @import "@/assets/css/mixin.scss";
// `
}
}
},
// }
productionSourceMap: false, // 调试异常 暂开启源码映射
// configureWebpack: config => {
// if (process.env.NODE_ENV === 'production') {
// return {
// output: { // 修改打包编译后的 文件名称 【模块名称-hash-毫秒时间戳.js】
// filename: `js/[name]-[contenthash:8]-${time}.js`,
// chunkFilename: `js/[name]-[contenthash:8]-${time}.js`
// }
// }
// }
// },
// chainWebpack: config => {
// config
// .plugin('provide')
// .use(webpack.ProvidePlugin, [{
// introJs: ['intro.js', 'introJs']
// }])
// },
// webpack-dev-server 相关配置
devServer: {
// 设置主机地址
host: 'localhost',
// 设置默认端口
port: 5002,
// 设置代理
proxy: {
'/api': {
// 目标 API 地址
target: 'http://localhost:7108/',
// 如果要代理 websockets
ws: true,
// 将主机标头的原点更改为目标URL
changeOrigin: true
},
}
},
pwa: {
iconPaths: {
favicon32 : 'favicon.ico',
favicon16 : 'favicon.ico',
appleTouchIcon: 'favicon.ico',
maskIcon : 'favicon.ico',
msTileImage : 'favicon.ico'
}
},
// css: {
// loaderOptions: {
// sass: {
// data: `@import "~@/assets/scss/variable.scss";`,//全局sass文件
// data: `@import "~@/assets/scss/mixin.scss";`//全局sass文件
// }
// }
// }
}
注意:因为我的vue-cli是4点多的版本,所以在引入terser-webpack-plugin插件的时候需要使用4代版本,这边用的4.2.3
npm i [email protected] -D