-
Notifications
You must be signed in to change notification settings - Fork 429
Description
UMD isn't currently compatible with JavaScript modules because import
and export
declarations would cause a syntax errors in engines that don't yet support modules. This makes UMD now less universal than it could be.
#125 makes UMD bundles loadable via import
statements, but the bundle will still write to globals (or use define
or exports
if available), so there are no useful symbols to import.
I think we can make importing UMD from JS modules better with a small shim that's imported instead and provides real exports.
There are two possible versions of the shim:
- A generic shim that exports a single object with all the UMD exports.
- A custom shim with a JS export for every UMD export
Generic Shim
The shim first sets up a global object to capture the UMD exports, then loads the UMD, then resets the global:
my-module-setup.js:
// Each UMD-JS-module shim needs it's _own_ setup module, even though the contents are the same, so that it evaluates before each UMD loads
window.exports = {}
my-module.js:
// We need a separate import to run code before the UMD module evaluates
import './my-module-setup.js';
// load the UMD module, which will populate window.exports
import './my-module.umd.js';
//export the UMD exports
export default let exports = window.exports;
// cleanup
window.exports = undefined;
Custom Shim
The custom shim works the same, but uses individual exports. This would likely be generated:
my-module.js:
// We need a separate import to run code before the UMD module evaluates
import './my-module-setup.js';
// load the UMD module, which will populate window.exports
import './my-module.umd.js';
//export the UMD exports
export const a = window.exports.a;
export const b = window.exports.b;
// cleanup
window.exports = undefined;
Custom shims would not support mutable bindings, ie you can't reassign an export from within the defining module.