如何阻止 webpack 的 `babel-loader` 缩小类名?

问题描述 投票:0回答:1

我的

webpack.config

中有以下内容
{
    test: /\.js$/,
    exclude: /node_modules/,
    use:
    { 
        loader: "babel-loader",
        options: {
            presets: [
                ["@babel/preset-env", { 
                    "targets": "last 1 chrome version"
                    }
                ]
            ],
            plugins: ["@babel/plugin-proposal-class-properties", "@babel/plugin-proposal-private-methods"]
        }
    }
}

如何在生产模式下阻止 webpack/babel 缩小/修改类名?

谢谢

webpack babeljs babel-loader
1个回答
0
投票

keep_classnames
terser 选项可以做到这一点,参见 terser Minify options.

keep_classnames
(默认值:
undefined
) - 通过
true
以防止丢弃或破坏类名。传递正则表达式以仅保留与该正则表达式匹配的类名。

例如

src/mock-link.js

export class MockLink {
  toString() {
    return 'mock link'
  }
}

src/app.js

import { MockLink } from './mock-link'

const mockLink = new MockLink();
console.log(mockLink);

webpack.config.js

const path = require('path');
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
  mode: 'production',
  entry: './src/app.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.(?:js|mjs|cjs)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', { targets: "defaults" }]
            ]
          }
        }
      }
    ],
  },
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin({
      terserOptions: {
        keep_classnames: true
      }
    })],
  }
};

dist/bundle.js

(()=>{"use strict";const n=new class MockLink{toString(){return"mock link"}};console.log(n)})();

如果我们将

keep_classnames
设置为
false
,则
dist/bundle.js
的输出:

(()=>{"use strict";const n=new class{toString(){return"mock link"}};console.log(n)})();

包版本:

"devDependencies": {
  "@babel/core": "^7.21.4",
  "@babel/preset-env": "^7.21.4",
  "babel-loader": "^9.1.2",
  "terser-webpack-plugin": "^5.3.7",
  "typescript": "^5.0.4",
  "webpack": "^5.80.0",
  "webpack-cli": "^5.0.2"
}
© www.soinside.com 2019 - 2024. All rights reserved.