swc-project / swc

Rust-based platform for the Web
https://swc.rs
Apache License 2.0
31.32k stars 1.23k forks source link

Mangle class method names #9626

Open levi-nz opened 1 month ago

levi-nz commented 1 month ago

Describe the feature

I was curious if a PR for mangling class method names would be accepted. This would be a (likely optional) feature that could be enabled in the minifier that would mangle method names in classes and interfaces (e.g. add() {} -> a() {}). The goal of this obviously would be to reduce output size of generated code after minification for code where private/non-exported classes and interfaces are used.

As far as I'm aware, the side effects of doing this are:

I'm not sure if we'd be interested in doing this, I'd be down to look into it if maintainers would be interested in having this as a feature, as it's a feature I'm interested in having available.

Also, side note: currently, the mangler doesn't check if an object or class is used in functions like JSON.stringify, so I think it would be good to at least look into adding detection for this so users can have this enabled without having to disable class property name mangling entirely. (I'm pretty sure you can filter out certain properties in the config, but I imagine this can become troublesome when dealing with large files)

I did try find if other minifiers do this, I don't believe terser does. I also checked Google Closure Compiler and it doesn't seem to either.

Babel plugin or link to the feature description

No response

Additional context

No response

kdy1 commented 1 month ago

I'm definitely interested in implementing this / maintaining this, and we should use some sort of mutex-protected cache for this.

We have a cache API exposed to JS side like https://github.com/swc-project/swc/blob/62edb3628b26036cdc767b31d59e109c3970497c/packages/core/src/index.ts#L14 which is defined as https://github.com/swc-project/swc/blob/62edb3628b26036cdc767b31d59e109c3970497c/bindings/binding_core_node/src/minify.rs#L85-L89 and used by swc_ecma_minifier like https://github.com/swc-project/swc/blob/62edb3628b26036cdc767b31d59e109c3970497c/crates/swc_ecma_minifier/src/lib.rs#L248

xastor commented 1 month ago

Terser does do this, and this is actually the one thing stopping me from adopting swc at the moment ;-) Also, class properties marked as private could also be mangled without any side effects.