mishoo / UglifyJS

JavaScript parser / mangler / compressor / beautifier toolkit
http://lisperator.net/uglifyjs/
Other
13.18k stars 1.25k forks source link

Invalid output when using global assignments #5927

Closed AshleyScirra closed 3 months ago

AshleyScirra commented 3 months ago

Uglify version (uglifyjs -V) 3.19.2

JavaScript input

globalThis.Unused = {};

globalThis.Namespace = {};
globalThis.Namespace.Foo = {
    bar: false,
};

The uglifyjs CLI command executed or minify() options used.

uglifyjs input.js --compress --beautify --output output.js

JavaScript output or error produced.

globalThis.Unused = {}, globalThis.Namespace.Foo = {
    bar: !(globalThis.Namespace = {})
};

Note in the output code there is an error as self.Namespace is not declared. For some reason the creation of Namespace has been moved to after it is used, so UglifyJS has transformed this from working code in to broken code.

If you comment out the line globalThis.Unused = {}; then it works correctly - so it looks like UglifyJS encountering the first global ends up in a state which then causes it to process the second global incorrectly.

AshleyScirra commented 3 months ago

The problem appears to be with the collapse_vars option. It can be worked around by passing false for that option, e.g.:

uglifyjs input.js --compress collapse_vars=false --beautify --output output.js

produces the following working output:

globalThis.Unused = {}, globalThis.Namespace = {}, globalThis.Namespace.Foo = {
    bar: !1
};
alexlamsl commented 3 months ago

Thanks for the detailed report − investigating.

alexlamsl commented 3 months ago

Patch released in uglify-js@3.19.3

AshleyScirra commented 3 months ago

Thanks!