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

bug: console.log + pure + minify + JSON.stringify, or even just a template literal #1879

Closed
revelt opened this issue Dec 22, 2021 · 2 comments

Comments

@revelt
Copy link

revelt commented Dec 22, 2021

Tested on 0.14.7.

There are three more cases related to console.log on --pure and --minify settings:


source index.js:

function test() {
	const obj = { "z": 1 };
	console.log(
		`obj: ${obj}`
	);
}

export { test }
npx esbuild index.js --platform=node --minify --target=node16 --outfile=out.js --pure:console.log

yields out.js:

function o(){`${{z:1}}`}export{o as test};

source index.js:

function test() {
	const obj = { "z": 1 };
	console.log(
		JSON.stringify(
			obj,
			null,
			4
		)
	);
}

export { test }

same command,

npx esbuild index.js --platform=node --minify --target=node16 --outfile=out.js --pure:console.log

yields out.js:

function n(){const o={z:1};JSON.stringify(o,null,4)}export{n as test};

source index.js:

function test() {
	const obj = { "z": 1 };
	console.log(
		`obj: ${JSON.stringify(
			obj,
			null,
			4
		)}`
	);
}

export { test }

same command,

npx esbuild index.js --platform=node --minify --target=node16 --outfile=out.js --pure:console.log

yields out.js:

function n(){const o={z:1};`${JSON.stringify(o,null,4)}`}export{n as test};

@evanw
Copy link
Owner

evanw commented Dec 22, 2021

Marking a function call as pure means "remove the function call but still evaluate the arguments" so this is expected behavior. The arguments will be preserved if they can't be proven to have no side effects, and esbuild considers running the ToString operation on a variable to be a side effect. I do not consider this to be a bug.

If you want to remove the console.log call entirely (including not evaluating the arguments), marking the function call as pure is not the way to do that. One way to do that is to move the console.log behind a conditional and then use --define to disable the conditional. An example would be doing something like this and then using something like --define:global.NO_LOG=true to remove the call entirely:

!global.NO_LOG && console.log(`obj: ${obj}`);

Closing as working as intended.

@evanw evanw closed this as completed Dec 22, 2021
@revelt
Copy link
Author

revelt commented Dec 22, 2021

Thank you for quick response! It makes sense.

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