Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The resulting code is minified but almost not mangled. This is how it looks like in the Google Chrome (beautified): Example of result did not mangled code 1/2. Example of result did not mangled code 1/2.

All properties names, lots of variables have their original names. Even with Terser's mangle options specified explicitly:

  • mangle: true,
  • sourceMap: false,
  • keep_fnames: false,
  • toplevel: true,

This is WebPack config:

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: './',
    }   

}

Did I miss something in the config?

like image 803
Oleg Zarevennyi Avatar asked Feb 04 '23 16:02

Oleg Zarevennyi


1 Answers

I believe in your original config you need to add mangle.properties to get your ES6 class methods and data members to be mangled. To avoid mangling external libraries, I "uniquely" name all my methods and data members to be mangled using a prefix strategy matching the regex below.

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

The niggly bits of this approach:

  • My naming currently doesn't match the naming in the external libraries I am using. There's no guarantee of this in future library releases.
  • It makes my original src a bit uglier.
like image 112
Ken Lin Avatar answered May 12 '23 04:05

Ken Lin