esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Support for specifying known globals

Open merceyz opened this issue 1 year ago • 1 comments

Description

I have a dependency that loads a large fallback implementation when typeof Intl.Segmenter === 'undefined' but I know that in my target environment typeof Intl.Segmenter === 'object' so I would like a way to inform esbuild about that so it can tree-shake the fallback.

Esbuild could potentially do this automatically based on the target and data from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter#browser_compatibility.

Code

The dependency: https://github.com/arcanis/slice-ansi/blob/eca8bfe4755e909e77fe11408f051d8ff0579df2/index.js#L12-L19

Reduced example:

export function segment(str) {
	if (typeof Intl.Segmenter === 'undefined') {
		return requireAndSegmentUsingFallbackDependency(str);
	}

	const segmenter = new Intl.Segmenter(`en`, { granularity: `grapheme` });

	return segmenter.segment(str);
}

Playground: https://esbuild.github.io/try/#YgAwLjIzLjAALS10YXJnZXQ9bm9kZTIwIC0tYnVuZGxlIC0tZm9ybWF0PWVzbSAtLXBsYXRmb3JtPW5vZGUgLS1taW5pZnkAZQBlbnRyeS5qcwBleHBvcnQgZnVuY3Rpb24gc2VnbWVudChzdHIpIHsKCWlmICh0eXBlb2YgSW50bC5TZWdtZW50ZXIgPT09ICd1bmRlZmluZWQnKSB7CgkJcmV0dXJuIHJlcXVpcmVBbmRTZWdtZW50VXNpbmdGYWxsYmFja0RlcGVuZGVuY3koc3RyKTsKCX0KCgljb25zdCBzZWdtZW50ZXIgPSBuZXcgSW50bC5TZWdtZW50ZXIoYGVuYCwgeyBncmFudWxhcml0eTogYGdyYXBoZW1lYCB9KTsKCglyZXR1cm4gc2VnbWVudGVyLnNlZ21lbnQoc3RyKTsKfQo

merceyz avatar Jul 11 '24 14:07 merceyz

I understand why you'd want this, and this is kind of a neat way to do it. However, having the compiler automatically remove safety checks kind of reminds me of the very subtle and surprising compiler behavior that C/C++ developers have to deal with. For example: https://pdos.csail.mit.edu/papers/ub:apsys12.pdf. From what I understand, this leads to a constant struggle for C/C++ developers against their compilers and can have serious implications for code in production. So I'm not sure how I feel about this suggestion.

evanw avatar Jul 12 '24 15:07 evanw

Closing this for the reason described above. This seems like too much of a foot-gun to me.

evanw avatar Feb 06 '25 20:02 evanw