I recently upgraded to Webpack 5 and I'm having some trouble importing UMD modules.
In particular, I'm trying to import Leaflet. Leaflet seems to export a UMD module created by rollup.js, which looks like this:
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.L = {})));
}(this, (function (exports) { 'use strict';
[...]
})));
As you can see, it first tries to use CommonJS (if exports
and module
is defined), then it tries to use AMD (if define
is defined), and otherwise it tries to put itself to the global scope by referencing this
from the module context.
Webpack (without any loaders) compiles it to this:
(function (global, factory) {
typeof exports === 'object' && "object" !== 'undefined' ? factory(exports) :
typeof define === 'function' && __webpack_require__.amdO ? define(['exports'], factory) :
(factory((global.L = {})));
}(undefined, (function (exports) { 'use strict';
[...]
})));
Concretely, what it did was:
- Replace
typeof module
with"object"
- Replace
define.amd
with__webpack_require__.amd0
- Replace
this
withundefined
During the build, webpack gives me a warning: export 'default' (imported as 'L') was not found in 'leaflet' (possible exports: )
. When I open the compiled bundle in the browser, I get the error Uncaught TypeError: Cannot set property 'L' of undefined
.
What happens is that CommonJS fails (because exports
is not defined), AMD fails (because define
is not defined) and finally setting the global also fails because this
is replaced with undefined
.
According to the Webpack docs, Webpack should universally support importing CommonJS and AMD modules, but it seems in this case neither of the two work.
What can I do to fix this?