Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax.
Named exports:
export { myFunction2, myVariable2 };
export let myVariable = Math.sqrt(2);
export function myFunction() {
}
After the export
keyword, you can use let
, const
, and var
declarations, as well as function or class declarations. You can also use the export { name1, name2 }
syntax to export a list of names declared elsewhere. Note that export {}
does not export an empty object — it's a no-op declaration that exports nothing (an empty name list).
Export declarations are not subject to temporal dead zone rules. You can declare that the module exports X
before the name X
itself is declared.
export { x };
const x = 1;
Default exports:
export { myFunction as default };
export default myFunction;
export default function () { }
export default class { }
Note: Names for export declarations must be distinct from each other. Having exports with duplicate names or using more than one default
export will result in a SyntaxError
and prevent the module from being evaluated.
The export default
syntax allows any expression.
As a special case, functions and classes are exported as declarations, not expressions, and these declarations can be anonymous. This means functions will be hoisted.
foo();
export default function foo() {
console.log("Hi");
}
export default function () {
console.log("Hi");
}
Named exports are useful when you need to export several values. When importing this module, named exports must be referred to by the exact same name (optionally renaming it with as
), but the default export can be imported with any name. For example:
const k = 12;
export default k;
import m from "./test";
console.log(m);
You can also rename named exports to avoid naming conflicts:
export { myFunction as function1, myVariable as variable };
You can rename a name to something that's not a valid identifier by using a string literal. For example:
export { myFunction as "my-function" };