There are four forms of import declarations:
Below are examples to clarify the syntax.
Named import
Given a value named myExport which has been exported from the module my-module either implicitly as export * from "another.js" or explicitly using the export statement, this inserts myExport into the current scope.
import { myExport } from "/modules/my-module.js";
You can import multiple names from the same module.
import { foo, bar } from "/modules/my-module.js";
You can rename an export when importing it. For example, this inserts shortName into the current scope.
import { reallyReallyLongModuleExportName as shortName } from "/modules/my-module.js";
A module may also export a member as a string literal which is not a valid identifier, in which case you must alias it in order to use it in the current module.
const a = 1;
export { a as "a-b" };
import { "a-b" as a } from "/modules/my-module.js";
Note: import { x, y } from "mod" is not equivalent to import defaultExport from "mod" and then destructuring x and y from defaultExport. Named and default imports are distinct syntaxes in JavaScript modules.
Default import
Default exports need to be imported with the corresponding default import syntax. The simplest version directly imports the default:
import myDefault from "/modules/my-module.js";
Since the default export doesn't explicitly specify a name, you can give the identifier any name you like.
It is also possible to specify a default import with 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";
or
import myDefault, { foo, bar } from "/modules/my-module.js";
Importing a name called default has the same effect as a default import. It is necessary to alias the name because default is a reserved word.
import { default as myDefault } from "/modules/my-module.js";
Namespace import
The following code inserts myModule into the current scope, containing all the exports from the module located at /modules/my-module.js.
import * as myModule from "/modules/my-module.js";
Here, myModule represents a namespace object which contains all exports as properties. For example, if the module imported above includes an export doAllTheAmazingThings(), you would call it like this:
myModule.doAllTheAmazingThings();
myModule is a sealed object with null prototype. The default export available as a key called default. For more information, see module namespace object.
Note: JavaScript does not have wildcard imports like import * from "module-name", because of the high possibility of name conflicts.
Import a module for its side effects only
Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values.
import "/modules/my-module.js";
This is often used for polyfills, which mutate the global variables.