evanw / esbuild

An extremely fast bundler for the web
https://esbuild.github.io/
MIT License
37.96k stars 1.13k forks source link

Support for specifying known globals #3831

Open merceyz opened 2 months ago

merceyz commented 2 months ago

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

evanw commented 2 months ago

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.