0

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 exist
  • exports doesn't exist
  • this 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?

Migwell
  • 18,631
  • 21
  • 91
  • 160
  • 1
    Extension environment is a standard browser environment so you can only use the standard ES modules directly. To use other types you either need to use a compiler/bundler or define those things it's looking for, like a global `exports` object or `define` function (you can write it yourself or find an existing one). – wOxxOm Apr 23 '20 at 03:49

1 Answers1

0

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").

Migwell
  • 18,631
  • 21
  • 91
  • 160