esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

ESBuild doesn't support constant folding expressions with enums imported from external files

Open esqu1 opened this issue 1 year ago • 1 comments

Repro:

// in test_enum.ts
export enum MyEnum {
  FIRST,
  SECOND,
  THIRD,
}

// in main.ts
import { MyEnum } from "./test_enum";

export function main() {
  if (0 == MyEnum.FIRST) {
    console.log("building the first");
  } else if (0 == MyEnum.SECOND) {
    console.log("building the second");
  } else {
    console.log("building something else");
  }
}

Running the command for bundling:

esbuild main.ts --bundle --outfile=out.js --minify --tree-shaking=true

should result in:

❯ cat out.js
(()=>{function e(){console.log("building the first")}})();

but instead gives

(()=>{function l(){0==0?console.log("building the first"):1==0?console.log("building the second"):console.log("building something else")}})();

which shows that ESBuild is not constant folding the enum in! It doesn't work either if the enum is marked as a const enum. For comparison, this DOES give the expected result if the enum is placed in the same file as where it's being used, main.ts.

Is this an issue where enum resolution comes after parsing/constant folding?

esqu1 avatar Oct 05 '23 15:10 esqu1

Is this an issue where enum resolution comes after parsing/constant folding?

Yes that’s correct, at least for cross-file enum inlining.

evanw avatar Oct 06 '23 01:10 evanw