esbuild: esbuild runtime introduces `exports` and `modules` which is not match with default browser env
esbuild version: 0.14.12
When I apply esbuild to following code (derived from CodeMirror)
(function() {
if (typeof exports == "object" && typeof module == "object") // CommonJS
{ console.log("CommonJS"); }
else if (typeof define == "function" && define.amd) // AMD
{ console.log("AMD"); }
else // Plain browser env
{ console.log("browser") ;}
}());
like esbuild --bundle a.js
, then esbuild generates following code
(() => {
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
// a.js
var require_a = __commonJS({
"a.js"(exports, module) {
(function() {
if (typeof exports == "object" && typeof module == "object") {
console.log("CommonJS");
} else if (typeof define == "function" && define.amd) {
console.log("AMD");
} else {
console.log("browser");
}
})();
}
});
require_a();
})();
In browser, original code shows browser
while generated code shows CommonJS
.
And I’m wondering whether esbuild can make exports
/module
variables match with browser env.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 17 (4 by maintainers)
This is already possible. One way to do that is use the
.mjs
extension on a per-file basis to indicate that a given file is ESM. Another way to do this more broadly is to put"type": "module"
inpackage.json
which indicates that all.js
files are ESM. This is not something specific to esbuild. It’s a standard convention from node: https://nodejs.org/dist/latest/docs/api/esm.html#enabling.@hyrious I understand detection might be possible. In that case, would it be possible to update esbuild to add a configuration that specifies “always assume all code is ESM”? E.g. do not try to emulate the CommonJS behavior, which would then get rid of the CommonJS snippet in the UMD definition and workaround the issue.