Skip to content

Unwrapping static switch cases with --minify-syntax #4176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Ragnar-Oock opened this issue May 7, 2025 · 2 comments
Open

Unwrapping static switch cases with --minify-syntax #4176

Ragnar-Oock opened this issue May 7, 2025 · 2 comments

Comments

@Ragnar-Oock
Copy link

Ragnar-Oock commented May 7, 2025

When a switch statement can be statically analyzed to have only one branch (because of a defined value, a resolved typeof, or any other static switch value), it should be unwrapped instead of remaining as a useless wrapper.

for example here is a polymorphic function that resolves an object differently based on the type of the first parameter : in esbuild playground

source for the minimal reproduction

function resolveSource(target) {
    switch ('string' /* infered by TS from "typeof target" */) {
        case 'string':
        case 'symbol': {
            console.log('service id syntax');
            return {};
        }
        case 'function': {
            console.log('target getter syntax');
            return {};
        }
        case 'object': {
            console.log('direct target syntax');
            return {};
        }
        default: {
            if (import.meta.env.DEV) {
                warn(new TypeError(`incorrect target provided to onEvent, typeof target === ${typeof target}, expected string, symbol, function or object`));
            }
            return {};
        }
    }
}

resolveSource("service");

When built with --minify-syntax, only the "string" branch remains :

function resolveSource(e) {
  switch ("string") {
    case "string":
    case "symbol":
      return console.log("service id syntax"), {};
  }
}

But it could be minified further, as only a single branch remains, and it has to be executed if the switch is evaluated, the body of the case should then be unwrapped to something like :

function resolveSource(e) {
  return console.log("service id syntax"), {};
}
@hyrious
Copy link

hyrious commented May 7, 2025

Interestingly Rollup doesn't delete much code for this case.

@Ragnar-Oock
Copy link
Author

terser however returns only console.log("service id syntax"); from the whole snippet (can't find a way to share from the REPL ). I don't think expecting esbuild to be that thorough would be any help as it's not esbuild's main concern tho.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants