Webpack打包优化之Terser


Terser

  • Terser 是一个 JS 的解释器(Parser)、Manler(绞肉机)/Compressor(压缩机)的工具集;
  • Terser 可以帮助我们压缩、丑化我们的 代码,让 bundle 变得更小;

    详细内容:https://github.com/terser/terser

命令行使用 Terser

  1. 安装 terser
npm i terser -D

2.开始使用

// js/index.js
const msg = "hello";
console.log(msg);

const foo = () => {
  console.log("foo");
};

foo();

function bar(num1, num2) {
  console.log("bar");
  console.log(arguments[0], arguments[1]);
}
bar();

const obj = {
  name: "obj",
  bar() {
    return "bar";
  },
};

// deed code
if (false) {
  console.log("hahahha");
}

执行 npx terser js/index.js -o js/index.min.js 输出结果为:

const msg="hello";console.log(msg);const foo=()=>{console.log("foo")};foo();function bar(num1,num2){console.log("bar");console.log(arguments[0],arguments[1])}bar();const obj={name:"obj",bar(){return"bar"}};if(false){console.log("hahahha")}

执行 npx terser js/index.js -o js/index.min.js -c arrows=true 输出结果为:

const msg="hello";console.log(msg);const foo=()=>{console.log("foo")};function bar(num1,num2){console.log("bar"),console.log(arguments[0],arguments[1])}console.log("foo"),bar();const obj={name:"obj",bar:()=>"bar"};

执行 npx terser js/index.js -o js/index.min.js -c -m toplevel=true 输出结果为:

const o="hello";console.log(o);const l=()=>{console.log("foo")};function n(o,l){console.log("bar"),console.log(arguments[0],arguments[1])}console.log("foo"),n();const c={name:"obj",bar:()=>"bar"};

常见的配置

Compress options

  • arrows (default: true) – Class and object literal methods are converted will also be converted to arrow expressions if the resultant code is shorter: m(){return x} becomes m:()=>x. To do this to regular ES5 functions which don’t use this or arguments, see unsafe_arrows.
  • arguments (default: false) – replace arguments[index] with function parameter name whenever possible.
  • dead_code (default: true) – remove unreachable code
  • drop_console (default: false) – Pass true to discard calls to console.* functions. If you wish to drop a specific function call such as console.info and/or retain side effects from function arguments after dropping the function call then use pure_funcs instead.

Mangle options

  • keep_classnames (default false) – Pass true to not mangle class names. Pass a regular expression to only keep class names matching that regex. See also: the keep_classnames compress option.
  • toplevel (default false) – Pass true to mangle names declared in the top level scope.

Webpack 中使用 Terser

  1. 安装 webpack webpack-cli html-webpack-plugin terser-webpack-plugin
npm i webpack webpack-cli html-webpack-plugin terser-webpack-plugin -D
  1. 文件目录结构
    .
    |-- ./build
    |   |-- ./build/index.html
    |   `-- ./build/js
    |       `-- ./build/js/main.ecac9b-bundle.js
    |-- ./package-lock.json
    |-- ./package.json
    |-- ./src
    |   |-- ./src/main.js
    |   `-- ./src/test-terser
    |       `-- ./src/test-terser/abc.js
    `-- ./webpack.config.js
// ./src/main.js
import "./test-terser/abc";

const message = "main";

console.log(message);
// ./src/test-terser/abc.js
const message = "hello word";
console.log(message);

const foo = () => {
  console.log("foo");
};

foo();

function bar(num1, num2) {
  console.log("bar");
  console.log(arguments[0], arguments[1]);
}
bar();

const obj = {
  names: "obj",
  bar() {
    return "bar";
  },
};

// deed code
if (false) {
  console.log("hahahha");
}
// ./webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { DefinePlugin } = require("webpack");
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
  mode: "production",
  entry: "./src/main.js",
  output: {
    clean: true,
    path: path.resolve(__dirname, "./build"),
    filename: "js/[name].[chunkhash:6]-bundle.js",
    chunkFilename: "js/[name].[contenthash:6]_chunk.js",
  },
  resolve: {
    extensions: [".js", ".ts", ".json"],
  },
  optimization: {
    minimize: true,
    minimizer: [
      // JS压缩插件:TerserPlugin
      new TerserPlugin({
        // 是否将注释剥离到单独的文件中,默认为 true
        extractComments: false,
        terserOptions: {
          compress: {
            arguments: true,
            // 没有使用的代码,但是希望保留下来
            // unused: false,
          },
          mangle: true,
          // toplevel: false,
          // keep_fnames: true,
        },
      }),
    ],
  },
  plugins: [
    new HtmlWebpackPlugin(),
    new DefinePlugin({
      BASE_URL: "'./'",
    }),
  ],
};

执行 npx webpack 就会生成 build文件夹,打开 js 文件夹就是打包结果


文章作者: PaoMo
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 PaoMo !
  目录