swc icon indicating copy to clipboard operation
swc copied to clipboard

Safe property mangling for local objects

Open rentalhost opened this issue 7 months ago • 2 comments

Describe the feature

Hello! I would like to propose enabling local objects to have their properties mangled based on the final mangle name.

The idea is that certain object properties can be safely renamed while others should remain intact. In cases where the property names are supplied by user input—making them potentially unknown—it’s important to preserve those names.

Conversely, when the object is used internally only (for example, accessed directly as sizes[x] rather than dynamically via an expression like sizes[x][y]), the property names are fair game for mangling.

Additionally, properties that are not used (such as a property named ununsed) could be considered for removal.

Babel plugin or link to the feature description

No response

Additional context

Consider the following example:

const sizes = {
  A4: { width: '21cm', height: '29.7cm' },
  Letter: { width: '8.5in', height: '11in', unused: "ununsed" }
};

export function printSize(paper) {
  const { width, height } = sizes[paper];
  console.log({ width, height });
}

Here, A4 and Letter are provided by the user via the paper parameter; hence, these names should not be mangled because the received value is potentially unknown. However, since sizes is not exported or used abstractly, its internal properties can be safely mangled.

The current output could look like this:

let sizes = {
    A4: { width: '21cm', height: '29.7cm' }, 
    Letter: { width: '8.5in', height: '11in', unused: "ununsed" } 
};

export function printSize(e) {
    let { width: i, height: t } = sizes[e];
    console.log({ width: i, height: t });
}

The ideal transformation, according to the proposal, might be:

let sizes = {
    A4: { i: '21cm', t: '29.7cm' }, 
    Letter: { i: '8.5in', t: '11in' } 
};

export function printSize(e) {
    let { i, t } = sizes[e];
    console.log({ width: i, height: i });
}

This approach enhances optimization by renaming internal property names where possible without impacting properties that are exposed or provided by external sources.

rentalhost avatar Apr 08 '25 23:04 rentalhost

Additionally, I was unsure whether this would be a duplicate of #9626.

rentalhost avatar Apr 08 '25 23:04 rentalhost

let me investigate and let you know

CodeMan62 avatar May 16 '25 13:05 CodeMan62