typescript - WebPack+TerserPlugin : mangle ignores properties and class names – poor quality of the mangled code

标签 typescript webpack terser

生成的代码被缩小,但几乎没有被破坏。这是它在 Google Chrome 中的样子(美化): Example of result did not mangled code 1/2. Example of result did not mangled code 1/2.

所有属性名称,许多变量都有其原始名称。 即使明确指定了 Terser 的 mangle 选项:

  • mangle:正确,
  • sourceMap: false,
  • keep_fnames:假,
  • 顶层:true,

这是 WebPack 配置:

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

module.exports = {
    entry: './src/scripts/index.ts',
    devtool: 'inline-source-map',
    module: {
        rules: [        
            {
                test: /\.tsx?$/,                
                use: {
                    loader: 'ts-loader',
                    options: { configFile: 'tsconfig-build.json' }
                },
                exclude: /node_modules/,                
            },
        ],        
    },
    resolve: {
        extensions: [ '.tsx', '.ts', '.js' ],
    },
    plugins: [ ],

    // PROBLEMS HERE:
    optimization: {        
        minimize: true,        
        minimizer: [new TerserPlugin({
            sourceMap: false,            
            extractComments: false, // To avoid separate file with licenses.
            terserOptions: {
                mangle: true,
                sourceMap: false,       
                //keep_classnames: false,
                keep_fnames: false,
                toplevel: true,                                
            },                     
        })],
    },

    output: {    
        path: path.resolve(__dirname, resultDirPath),
        filename: 'main.js',
        publicPath: './',
    }   

}

我是否遗漏了配置中的某些内容?

最佳答案

我相信您的原始配置需要添加 mangle.properties让你的 ES6 类方法和数据成员被破坏。为了避免损坏外部库,我使用与下面的正则表达式匹配的前缀策略“唯一”命名要损坏的所有方法和数据成员。

            new TerserPlugin({
                terserOptions: {
                    mangle: {
                        properties: {
                            regex: /(^P1|^p1|^_p1)[A-Z]\w*/
                        }
                    }
                }
            })
        "terser-webpack-plugin": "^2.2.1",

这种方法的细节:

  • 我的命名当前与我正在使用的外部库中的命名不匹配。在未来的库版本中无法保证这一点。
  • 这让我原来的 src 有点难看。

关于typescript - WebPack+TerserPlugin : mangle ignores properties and class names – poor quality of the mangled code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58835084/

相关文章:

typescript - 如何在 TypeScript 中创建扩展类型?

javascript - Node.js 绝对引用路径

Typescript "error TS2532: Object is possibly ' undefined'"即使在未定义检查之后

javascript - 如何手动触发 webpack 开发服务器的监视/重新加载?

webpack - "DevTools failed to parse SourceMap: webpack://"和 monorepo lerna 包源映射重写

node.js - 如何让 go to catch 语句出错

javascript - 以在新构建上传时不需要清除缓存的方式实现缓存

node.js - Webpack热重载ENOENT没有这样的文件或目录

angular - 来自 Terser 的 scrips.xxx.js 中的错误无效分配

java - Heroku 构建失败,因为缺少 npm