For more tips like this, sign up to the weekly newsletter!
How to use named and default imports together with ES6 modules
When a module has either a default or named exports, importing is trivial.
For a modules.js
that has a default export:
export default "default"; // exports the String "default"
The import
specifies the name:
import module from "./module.js";
And with named exports:
export const b = "b"; // exports the String "b"
The value can be imported by name:
import {b} from "./module.js";
And can be renamed with as
:
import {b as newb} from "./module.js";
But how to import both the default and the named imports in one statement?
Use named and default imports together
The default export is exported under the name default
. Whenever you import that, the default will be used.
This way, you can give it a name:
import {default as mod, b as newb} from "./module.js";
This import
declares the default export as mod
and b
as newb
.
As an alternative, separate the two types of imports with a comma:
import mod, {b as newb} from "./module.js";