Modern JS: import and export
Source: Dev.to

This article was originally published on bmf-tech.com.
※Reprinted from the Innovator Japan Engineers’ Blog.
What is export
export is a statement that allows you to expose functions, variables, objects, classes, etc., from a file so that they can be imported elsewhere.
Named exports
You explicitly name the elements you want to export.
export { fooFunction };
export { fooFunction, barFunction, /* … */ };
export const foo = 'bar';
export let foo, bar, /* … */;
export class Foo { /* … */ }Default exports
You use the default keyword when you want to export a single “default” value from a module.
export default function fooFunction() { /* … */ }
export default class Bar { /* … */ }Note:
var,let, andconstcannot be used withexport default.
What is import
import loads functions, variables, and objects that were exported from another file.
import { foo } from "Foo";
import { foo, bar } from "FooBar";
import { foo as bar } from "Foo"; // alias
import { foo as bar, bar as foo } from "FooBar";
import "FooBar"; // import for side effects onlyImported bindings are available in the current (local) scope.
How to import default elements defined with export default
Import the default export directly:
import fooDefault from "Bar";If you also need named exports from the same module, list them after the default import:
import fooDefault, { foo, bar } from "FooBar";Example of exporting / importing a class
Exporting a named class and a default class
export.js
export class Foo {
fooFunction() {
return 'foo';
}
}
export default class Bar {
barFunction() {
return 'bar';
}
}import.js
import { Foo } from './export'; // named import
import Bar from './export'; // default import
const objFoo = new Foo();
const objBar = new Bar();
console.log(objFoo.fooFunction()); // foo
console.log(objBar.barFunction()); // barExporting a factory function that creates an instance
export.js
class Foo {
fooFunction() {
return 'foo';
}
}
function createFoo() {
return new Foo();
}
export default createFoo;import.js
import createFoo from './export';
const fooInstance = createFoo();
console.log(fooInstance.fooFunction()); // fooSummary
Understanding the export and import specifications is essential, as they are heavily used in modern frameworks such as Vue.js and React.