Skip to content

Allow esbuild to reuse mangled property names in certain cases #4453

@LoganDark

Description

@LoganDark

When mangling props, esbuild assumes that any property can be added to or encountered on any object, and therefore that there should be no collisions between mangled names. This is a reasonable default.

However, I think this can be improved in certain cases. For example, in a greenfield project where I know that my code will never interpret one object as another, it seems wasteful for esbuild not to reuse mangled property names in places that do not encounter different types.

For example, let's say I have two types, Type A and Type B. They each have different properties, and I never cast or interpret Type A as Type B or vice versa. In this case, esbuild technically does not need to avoid Type A's mangled property names when generating Type B's, because code that operates on Type B does not encounter Type A.

There is currently no way to tell esbuild that two sets of properties are disparate enough that mangled names can be reused between them. This means that any property name that is unique in the source will always be unique in the output.


My proposal would be to allow specifying a pattern for "property namespace". For example, ever since learning that mangled property names share a global namespace, in this project I always prefix my property names with the name of the containing type, so that properties across different types don't get confused.

For example, let's say TypeA_prop1_ and TypeB_prop1_ are different properties in the source code, but because they're on different objects and if I know that code will never try to use one on the wrong object, esbuild could actually mangle them to the same name. This can result in bundle size savings, since it would take longer for esbuild to get pushed into using longer mangled names, due to being able to reuse some of them.

A namespacing pattern for this example might be ^[A-Z][^_]*_(?=.), which matches the leading TypeA_/TypeB_ in cases where it's not the whole property name. Properties in a namespace would be able to mangle to names that have occurred in other namespaces, but of course not in the same namespace.

For compatibility, no namespaced property would mangle to a name shared with an un-namespaced property (nor vice versa). Only mangled names of namespaced properties would be re-used for other namespaced properties.


I may prepare a PR that adds this functionality soon.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions