Appearance
ES6 Modules: export and import
JavaScript modules help organize and reuse code across files using the export and import key words.
Named Imports/Exports
The following are named examples where the export and import use the name of the values:
js
// file.js
export const Temperature = 70;
export function add(a, b) {
return a + b;
}
export class Animal {
//...
}js
import { Temperature, add, Animal } from './file';You can also use the as key word to rename the value:
js
import { Temperature as temperature } from './file'
console.log(temperature) //70;Default Exports
Each file/module can have one default export.
js
// file.js
export default function Component() {
// ...
}When importing default exports, the name can be anything
js
import RenamedComponent from './file';Import Everything
Multiple exports from a file can be imported at once as a single object:
js
export function helperFn() {...}
export const NUM = 1;js
// all exports from ./util are in the utils object
import * as utils from './util';
utils.helperFn()
utils.NUMRe-Exporting / index.js
Sometimes it can be useful to re-export values from another file:
js
export { add } from './util';
export * as util from './util';
export * from 'util';This is especially useful for the index.js file when grouping related files into a directory.
Say we have this directory structure:
- CommonComponent
- Button.jsx
- TextField.jsx
- Dialog.jsx
- index.jsin the index.js file we can export these components as such:
js
export { default as Button } from './Button';
export { default as TextField } from './TextField';
export { default as Dialog } from './Dialog';and when we want to import them we can directly import from /CommonComponent:
js
import { Button, TextField, Dialog } from './CommonComponent';
// instead of doing it individually like:
import Button from './CommonComponent/Button';
import TextField from './CommonComponent/TextField';
import Dialog from './CommonComponent/Dialog';