evanw / esbuild

An extremely fast bundler for the web
https://esbuild.github.io/
MIT License
37.85k stars 1.12k forks source link

Tree shake template literals #3472

Open KTibow opened 9 months ago

KTibow commented 9 months ago

Open demo

esbuild shouldn't ship bye in the bundle, it should only ship hi.

Now I know esbuild can't tell if t has side effects. However, while invoking t with PURE tree shakes, esbuild still doesn't tree shake the template literal no matter how much PUREing you do.

hyrious commented 9 months ago

Interestingly, rollup does not support pure annotation before tagged template literals too, related issue here: https://github.com/rollup/rollup/issues/4035

On the other hand, rollup does support /* @__NO_SIDE_EFFECTS__ */ to mark the function (instead of a call) as pure:

/* @__NO_SIDE_EFFECTS__ */
function func(foo) {
  console.log(foo)
}

var foo = func`literal`  // <-- tree shaked!

esbuild currently preserves this magic comment (changelog: 0.18.1), so I guess you can just use this way to write your code.

evanw commented 9 months ago

You can annotate any arbitrary expression as pure (including template literals) for all tools that support pure annotations (including esbuild and Rollup) by putting it in an IIFE.

KTibow commented 9 months ago

That's not as clean (or performant) as it being implemented in esbuild but that's definitely much better than nothing

KTibow commented 9 months ago

Also it's worth noting that Rollup

evanw commented 9 months ago

With the latest release, esbuild will now inline IIFEs that return an expression when minifying, so there should no longer be any performance impact from doing this.