一、安裝Terser-webpack-plugin
在使用Terser-webpack-plugin之前,需要先安裝。根據項目所使用的包管理工具,運行以下命令:
npm install terser-webpack-plugin -- save-dev
或者使用yarn:
yarn add terser-webpack-plugin --dev
二、為什麼需要Terser-webpack-plugin
構建項目時,你需要優化項目中的js文件。Terser-webpack-plugin是Webpack的內置插件UglifyJS的替代方案。它提供了更好的默認參數以及更小的bundle大小。因此,使用Terser-webpack-plugin可以幫助我們更好的優化Webpack項目。
三、如何使用Terser-webpack-plugin
我們需要在Webpack.config.js文件中添加如下代碼來使用Terser-webpack-plugin。
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimizer: [new TerserPlugin()],
},
};
以上代碼將Terser-webpack-plugin添加到了Webpack的minimizer數組中。當運行webpack打包命令時,Terser-webpack-plugin會自動壓縮代碼。
四、Terser-webpack-plugin常用選項
1、parallel
定義TerserPlugin使用的worker數量。worker用於並行運行Terser。該選項的默認值是 os.cpus().length – 1。
new TerserPlugin({
parallel: true,
}),
2、terserOptions
定義Terser的配置選項。常用選項有:
- compress: 定義壓縮行為的配置對象
- mangle: 定義混淆選項的配置對象
- output: 定義輸出選項的配置對象
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true,
},
output: {
comments: false,
},
},
}),
3、extractComments
將注釋提取到單獨的文件中。默認值為 false,設置為 true 可以將注釋提取到與打包文件同名的 .LICENSE 文件中。
new TerserPlugin({
extractComments: true,
}),
4、test/include/exclude
test 和 include/exclude 選項用於細粒度地控制哪些文件要壓縮。其中,test 是一個匹配文件的正則表達式。include 和 exclude 是一組匹配載入器或者文件的條件數組。
new TerserPlugin({
test: /\.js(\?.*)?$/i,
exclude: /node_modules/,
terserOptions: {
compress: {
unused: true,
dead_code: true,
},
},
}),
五、總結
本文對Terser-webpack-plugin進行了詳細介紹,包括安裝、使用以及參數等。希望本文能夠幫助大家更好的優化Webpack項目。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/241836.html