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

esbuild "comment" to strip the next line during bundling? #3849

Closed
Pomax opened this issue Jul 27, 2024 · 2 comments
Closed

esbuild "comment" to strip the next line during bundling? #3849

Pomax opened this issue Jul 27, 2024 · 2 comments

Comments

@Pomax
Copy link

Pomax commented Jul 27, 2024

I was reading through #2006 because I have a bunch of code in a single file along the line of

const DEBUG = true;

...

if (DEBUG) console.log('lemon cake deserves real cream');

and was hoping to treeshake those out of existence (without minification) when DEBUG is false as any code path conditional on false is dead code and can be safely "shaken out". However, that's not really what happens, and if I read into issue 2006 and use a pattern DEBUG && console.log(....) instead, then the bundle ends up with a bunch of spurious DEBUG && void 0; rather than just "nothing.

For cases like these, it would be super nice to have something like // @esbuild strip next-line or something combined with --allow-strip as CLI argument so that esbuild knows to just gobble input until it's passed the next line of code. e.g.:

// @esbuild strip next-line
const DEBUG = true;

...

// @esbuild strip next-line
if (DEBUG) console.log('lemon cake deserves real cream');
runSomeThing();

would essentially pass the input as if it was:

...

runSomeThing();

Which would make for a much nicer bundle.

(And because it would control the parser, it doesn't even need to know "what" it's stripping. If the resulting bundle is broken, that's on the person adding the strip comment, not esbuild)

@evanw
Copy link
Owner

evanw commented Jul 28, 2024

I recommend that you use labels instead of comments: https://esbuild.github.io/api/#drop-labels. It's an existing feature and it uses real syntax instead of magic comments so it's more robust to code transformations than magic comments would be. It also has the benefit that you can toggle different names on and off independently for finer control. Here's an example (the label names are arbitrary and is up to you):

https://esbuild.github.io/try/#dAAwLjIzLjAALS1kcm9wLWxhYmVscz1lc2J1aWxkX3N0cmlwX3RoaXMAZXNidWlsZF9zdHJpcF90aGlzOgpjb25zb2xlLmxvZygnbGVtb24gY2FrZSBkZXNlcnZlcyByZWFsIGNyZWFtJyk7CnJ1blNvbWVUaGluZygpOw

@Pomax
Copy link
Author

Pomax commented Jul 28, 2024

completely missed that part of the docs, thank you!

@Pomax Pomax closed this as completed Jul 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants