Load a module conditionally or on demand
"A lot of the most exciting new browser features are built on top of modules, not classic scripts. That means if you want to use any of these features, your code needs to be deployed as real modules, not transpiled to ES5 and loaded via classic script tags..." - Philip Walton, Google Engineer
// This inserts myModule into the current scope, containing all
// the exports from the module in the file located in /modules/my-module.js.
import * as myModule from '/modules/my-module.js';
// Accessing the exports means using the module name ("myModule"
// in this case) as a namespace.
myModule.doAllTheAmazingThings();
// This inserts myExport into the current scope
import { myExport } from '/modules/my-module.js';
// Can be called as a function
myExport();
// This inserts myExport into the current scope
import { foo, bar } from '/modules/my-module.js';
// Can be called as functions
foo();
bar();
// This inserts shortName into the current scope
import {reallyReallyLongModuleExportName as shortName}
from '/modules/my-module.js';
// Can be called as a function
shortName();
// This runs the module's global code,
// but doesn't actually import any values
import '/modules/my-module.js';
// This works with dynamic imports too
(async () => {
if (somethingIsTrue) {
// import module for side effects
await import('/modules/my-module.js');
}
})();
// The simplest version directly imports the default:
import myDefault from '/modules/my-module.js';
// It is also possible to use the default syntax with the ones
// seen above (namespace imports or named imports). In
// such cases, the default import will have to be declared
// first. For instance:
import myDefault, * as myModule from '/modules/my-module.js';
import myDefault, {foo, bar} from '/modules/my-module.js';
// Works with dynamic imports. You need to destructure and
// rename the "default" key from the returned object.
(async () => {
if (somethingIsTrue) {
const { default: myDefault, foo, bar } = await import('/modules/my-module.js');
}
})();