2

I have a simple TypeScript class, which I transpile to ES5 and then bundle with webpack 2 and minimize with UgilfyJS3.

I would expect UgilfyJS to also mangle the function name showGreeting() (see code below), but in the minified js-file, it is not. Is there any other option I can set to minify the function names or am I doing something worng? I understand that the variable name is not mangled, but why not the function name?

Here is the original TypeScript file:

export class Greeter {
    constructor(greeting: string) {
        this.greeting = greeting;
    }

    greeting: string;
    showGreeting() {
        console.log(this.greeting);
    }
}

const myGreeter = new Greeter("hello, world");
myGreeter.greeting = "howdy";
myGreeter.showGreeting();

And this is the webpack.config including UglifyJS:

const path = require('path');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
    entry: './test.ts',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    devtool: "source-map",
    resolve: {
        extensions: ['.ts', '.tsx', '.js']
    },
    module: {
        loaders: [
          { test: /\.tsx?$/, loader: 'ts-loader' }
        ]
    },
    plugins: [
        new UglifyJSPlugin({
            mangle: {
                toplevel: true,
                eval: true
            }
        }), 
]
};

And the generated output Javascript contains the following lines:

[function (e, t, r) {
            "use strict";
            Object.defineProperty(t, "__esModule", {
                value: !0
            });
            var n = function () {
                function e(e) {
                    this.greeting = e
                }
                return e.prototype.showGreeting = function () {
                    console.log(this.greeting)
                },
                e
            }
            ();
            t.Greeter = n;
            var o = new n("hello, world");
            o.greeting = "howdy",
            o.showGreeting()
        }
    ]);
Dominic
  • 2,863
  • 2
  • 18
  • 34

1 Answers1

4

Class members are object properties, and UglifyJS doesn't mangle property names. Here is an explanation.

The Closure compiler from Google can do the job. But it is hard to use, with limitations.

Paleo
  • 16,013
  • 3
  • 44
  • 62
  • An "ugly" alternative is to prefix anything which is a class member with an underscore (variables, functions) and configure Uglify to mangle all properties starting with "_" - mangleProperties: { regex: /^_/ } – Maciej Krawczyk Sep 02 '20 at 06:36