The UMD module definition is approximately this:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'b'], factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
factory(exports, require('b'));
} else {
// Browser globals
factory((root.commonJsStrict = {}), root.b);
}
}(this, function (exports, b) {
//use b in some fashion.
// attach properties to the exports object to define
// the exported module properties.
exports.action = function () {};
}));
The issue is that Chrome Extensions don't support any of these methods of exporting the module:
define
doesn't existexports
doesn't existthis
isn't bound to window
For this reason, it seems that UMD modules fail in Chrome Extension environments. Is there any workaround to get a UMD module to correctly export into the window
object in a Chrome Extension?
As @wOxxOm has correctly pointed out, the Chrome Extension environment is the same as the browser, and this
is indeed bound to window
, so UMD modules can and should work with extensions.
It turns out the actual problem is that babel was producing a bundle with this
replaced by undefined
, which is the problem outlined and resolved in this issue: How to stop babel from transpiling 'this' to 'undefined' (and inserting "use strict").