Skip to content
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

Tree shake template literals #3472

Open
KTibow opened this issue Nov 4, 2023 · 5 comments
Open

Tree shake template literals #3472

KTibow opened this issue Nov 4, 2023 · 5 comments

Comments

@KTibow
Copy link

KTibow commented Nov 4, 2023

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
Copy link

hyrious commented Nov 4, 2023

Interestingly, rollup does not support pure annotation before tagged template literals too, related issue here: rollup/rollup#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
Copy link
Owner

evanw commented Nov 18, 2023

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
Copy link
Author

KTibow commented Nov 18, 2023

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

@KTibow
Copy link
Author

KTibow commented Nov 18, 2023

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

@evanw
Copy link
Owner

evanw commented Nov 19, 2023

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.

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