有的时候咱们想要同时生成压缩和未压缩的文件,好比咱们构建 lib 包的时候,咱们但愿用户可以使用压缩事后的代码文件做为 cdn 文件,最简单的一个方式就是经过指定环境变量,好比指定 MINIFY,以下:webpack
const path = require('path')
const isMinify = process.env.MINIFY
/** * @type {import('webpack').Configuration} */
const config = {
entry: {
index: './src/index.js'
},
output: {
filename: isMinify ? '[name].min.js' : '[name].js',
path: path.join(__dirname, 'dist')
},
devtool: 'cheap-source-map',
optimization: {
minimize: isMinify ? true : false
}
}
module.exports = config
复制代码
咱们在使用的时候经过指定环境变量就能够打包成不一样的版本:git
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build:min": "MINIFY=1 webpack --config=webpack.config.js",
"build": "webpack --config=webpack.config.js"
}
复制代码
不过这样的缺点就是咱们须要运行两次。github
第二个方法是安装 unminified-webpack-plugin,经过这个插件能够生成没有压缩的文件:web
const path = require('path')
const UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
/** * @type {import('webpack').Configuration} */
const config = {
entry: {
index: './src/index.js',
},
output: {
filename: '[name].min.js',
path: path.join(__dirname, 'dist')
},
devtool: 'cheap-source-map',
plugins: [
new UnminifiedWebpackPlugin({})
]
}
module.exports = config
复制代码
不过这个有个缺点就是未压缩的文件没有 sourcemap。ui
第三种方法经过指定多个打包入口,而后手动指定压缩插件(uglifyjs、terser等)压缩哪些文件,如咱们指定 index.min.js
这个文件才须要压缩,配置以下:spa
const path = require('path')
const TerserWebpackPlugin = require('terser-webpack-plugin');
/** * @type {import('webpack').Configuration} */
const config = {
entry: {
index: './src/index.js',
'index.min': './src/index.js'
},
output: {
filename: '[name].js',
path: path.join(__dirname, 'dist')
},
devtool: 'cheap-source-map',
optimization: {
minimize: true,
minimizer: [
new TerserWebpackPlugin({
include: /min/,
sourceMap: true
})
]
}
}
module.exports = config
复制代码
关键点以下:插件
这个时候生成的就完美了。code
最后是一个广告贴,最近新开了一个分享技术的公众号,欢迎你们关注👇regexp
本篇文章由一文多发平台ArtiPub自动发布cdn