Terser: Cached variables can lead to incorrect toplevel trasnpilation

Created on 9 Nov 2018  路  6Comments  路  Source: terser/terser

Bug report or Feature request?

Bug

Version (complete output of terser -V)

3.10.11

Complete CLI command or minify() options used

// Terser options
{
    toplevel: true,
    mangle: true,
    nameCache: {
        vars: {
            props: {
                $add: 'foo'
            }
        },
        props: {
            props: {}
        }
    }
}

terser input

// a.js
import { add as someAdd } from './b';

console.log( someAdd( 1, 2 ) );
// b.js
export function add( x, y ) {
    return x + y;
}

terser output or error

export function foo(n,r){return n+r}
import{add as o}from"./b";console.log(o(1,2));

Expected result

The original exported add function should stay as it is. Eventually, its name should be transformed along with all its occurrences in imports.

Most helpful comment

@ma2ciek Please try #166 and report your findings.

All 6 comments

I've created a repository with this bug reproducible: https://github.com/ma2ciek/terser-bug.

Thanks for the detailed bug report.

Initially I thought that the nameCache was contrived and couldn't be created through normal minification, but that's not the case:

$ rm -f cache.json

$ echo 'function add(){Math.random();} add(); add();' | terser --toplevel -mc --name-cache cache.json
function n(){Math.random()}n(),n();

$ cat cache.json && echo
{"vars":{"props":{"$add":"n"}}}

$ echo 'export function add(x, y){ return x + y; }' | terser --toplevel -mc --name-cache cache.json
export function n(n,r){return n+r}

I have a fix for this.

Other bug variations:

$ cat cache.json && echo
{"vars":{"props":{"$add":"n"}}}

$ echo 'export class add{}' | terser --toplevel -mc --name-cache cache.json
export class n{}

$ echo 'export var add = 1;' | terser -mc --name-cache cache.json
export var n=1;

$ echo 'export let add = 1;' | terser -mc --name-cache cache.json
export let n=1;

$ echo 'export const add = 1;' | terser -mc --name-cache cache.json
export const n=1;

$ echo 'export let sub = 0, add = 1;' | terser --module -mc --name-cache cache.json
export let sub=0,n=1;

$ echo 'export let {x: add} = obj;' | terser --module -mc --name-cache cache.json
export let{x:n}=obj;

Any other failing scenarios?

Okay, I have a more general fix that should handle all export declaration scenarios.

@ma2ciek Please try #166 and report your findings.

Thanks for the quick fix! It works perfectly on that branch for our needs. I've tested it on our codebase and no error has occured after the minification.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ttyerl picture ttyerl  路  3Comments

Shmasya picture Shmasya  路  6Comments

dtruffaut picture dtruffaut  路  3Comments

maksimr picture maksimr  路  7Comments

zbream picture zbream  路  6Comments