esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Tree shake template literals

Open KTibow opened this issue 2 years ago • 5 comments

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.

KTibow avatar Nov 04 '23 02:11 KTibow

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.

hyrious avatar Nov 04 '23 02:11 hyrious

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.

evanw avatar Nov 18 '23 19:11 evanw

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

KTibow avatar Nov 18 '23 19:11 KTibow

Also it's worth noting that Rollup

  • if the function is a special case (v) => v or has no_side_effects: does tree shaking fine
  • in other cases: just runs it as an expression instead of declaring a variable

KTibow avatar Nov 18 '23 20:11 KTibow

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.

evanw avatar Nov 19 '23 07:11 evanw