zloirock / core-js

Standard Library
MIT License
24.6k stars 1.66k forks source link

Fix to avoid minification problem with esbuild #1368

Open diegovdev opened 2 months ago

diegovdev commented 2 months ago

esbuild will minify this to 1.toString (removing the trailing zero) which will result in a syntax error in the browser. A trailing zero will be removed during minification but a trailing 1 wont.

See image below:

SCR-20240920-kuxj
diegovdev commented 2 months ago

Proof that it's the same resulting toString method, in the browser console:

image
0f-0b commented 2 months ago

esbuild actually minifies 1.0.toString to 1 .toString (note the space), so it must be some other tool that misprinted the code. The bug is in that tool, not core-js.

diego-carvallo commented 1 month ago

@zloirock we use Vite (https://vite.dev/) which under the hood uses esbuild. We tried enforcing esbuid configs and nothing worked, we tried to use terser as minifyer but we got the same error as with esbuild. It makes sense that some tooling on the road will remove unecesary spaces in 1 .toString, you shouldn't be relying on a space to be a solution.

The fix I proposed here is just preventing using a zero 0 so that you don't run any more into minifyers trying to modify the expression. For a minifyer 1.0 is safely reduced to just 1, they have no configs to prevent this behavior.

It's funny how such a small and efficient fix is just rejected, this for sure would have prevented other people to run into this annoyance. Our only solution now is to have this ugly plugin for Vite that just pollutes every project we have that depends on core-js.

function corejsMinificationFix() {
  return {
    name: 'corejsMinificationFix',
    enforce: 'post',
    apply: 'build',
    transform(code, id) {
      if (id.includes('xxxx/node_modules/core-js/internals/uid.js')) {
        return {
          code: code.replace('1.0.toString', '1.1.toString'),
          map: null,
        }
      }
    },
  }
}
zloirock commented 1 month ago

@diego-carvallo I'm curious: Did you miss my comment above? It's not a core-js bug, but I'm ready to accept this PR as a workaround in case you at least report it to the source of this bug. Accepting this PR without that is irresponsible since it will cause the same problems in case of such a valid JS expression in other code — and there were already examples of this mentioned above. Is reporting this to the source of the problem so hard to do and easier to throw a tantrum?

diego-carvallo commented 2 weeks ago

Here is the issue reported to ESBuild https://github.com/evanw/esbuild/issues/3975