'Terser keep (don't mangle) a specific function name

Is there a way to not mangle only one function name? A comment in the code would be easiest, but I guess this could be done by specifying a custom "nameCache" ? But I don't know how that works.



Solution 1:[1]

I couldn't figure this out, but I already had the function name so I stored the function name on the webpage in an attribute that I could find later with JavaScript. e.g.

function bob() {
  console.log('hello');
}

document.querySelector('#myid').setAttribute('data-function-name', bob.name);
<span id="myid">for example make this style="display:none;"</span>

Solution 2:[2]

To prevent terser from mangling a particular symbol, you need to add it to terser's reserved list. This can be done in your terser options file:

{
    "mangle":
    { 
        "properties":
        {
            "reserved": ["symbolToNotMangle", "anotherSymbolToPreserve"]
        }
    }
}

If you are not already using a terser options file, you would save that off to (for example) terser_options.json and tell terser to use it like so:

terser ... --config-file terser_options.json

You can also just list the reserved symbols on the command line if you prefer:

terser ... -m reserved=['symbolToNotMangle','anotherSymbolToPreserve']

https://github.com/terser/terser#cli-mangle-options

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AaronJ
Solution 2 Haydentech