-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Description
Bug Report
Current Behavior
If you apply the transform-es2015-modules-umd plugin to a module, the resulting code cannot be executed as an ES module.
The problem stems from the fact that the generated code passes this as the first parameter to the UMD function. When executed as an ES module, this is undefined at the script scope so undefined gets passed into the UMD function. globalThis and window are both defined in the browser context (I haven't tested NodeJS), so the UMD module can still function if something besides this was passed in to the UMD function.
Input Code
<!DOCTYPE html>
<html lang='en'>
<head><meta charset='utf-8'></head>
<body>
<script type='module' src='my-module.js'></script>
</body>
</html>Original ES module (my-module.mjs):
export default 42;Generated UMD module (my-module.js):
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.input = mod.exports;
}
})(this, function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var _default = 42;
_exports.default = _default;
});Expected behavior/code
The module would execute when loaded as an ES module.
Babel Configuration (.babelrc, package.json, cli command)
{
globals: {
"webextension-polyfill": "browser",
},
exactGlobals: true,
}Environment
- Babel version(s):
"babel-plugin-transform-es2015-modules-umd": "^6.24.1" - Node/npm version: Unknown
- OS: Unknown
- Monorepo: No.
- How you are using Babel: Grunt
Possible Solution
Change the UMD function call to pass globalThis || window || this as the first parameter, rather than passing this as the first parameter. This change will make the module fully functional when loaded as an ES module, while still retaining the current behavior when loaded as a script.
Additional context/Screenshots
The problem showed up for me over at the webextension-polyfill page, spelunking lead me to realize the problem is with Babel, which that project uses for transpiling to UMD.
mozilla/webextension-polyfill#202