RosenblogNavigate back to the homepage

ES6 Modules

Martin Rosenberg
August 14th, 2019 · 1 min read

Photo by Raphael Koh on Unsplash

Perhaps in the future, I’ll go into a bit more detail, but for now, here are the basic recipes. Note that ES6 modules don’t work (by default, for now) in Node, or in outdated browsers; you’ll want to use Babel, TypeScript, or some other compiler to convert these to whichever module format you want (e.g. CommonJS for Node).

Exports

Named exports

You can have as many named exports as you want, in any combination of formats.

1// Export a variable inline.
2export const isGreen = (color) => color === 'green'
3
4// Export a function declaration inline.
5export function isPink (color) { return color === 'pink' }
6
7// Export a class inline.
8export class LittleBox { /* ... */ }
9
10// Export at the bottom.
11const blue = 'blue'
12function yellow () { return 'yellow' }
13class Hillside {}
14
15export { blue, yellow, Hillside }

Default exports

You can only have (up to) one default export per file/module.

1// Export variable inline. This causes problems in debugging
2// because the variable has no name for stack traces.
3export default ({ profession }) => profession === 'doctor'
4
5// Export variable separately.
6const isDoctor = ({ profession }) => profession === 'doctor'
7export default isDoctor
8
9// Export function declaration inline. This causes the same
10// problems if you don't name the function.
11export default function ({ profession }) { return profession === 'lawyer' }
12export default function isLawyer ({ profession }) { return profession === 'lawyer' }
13
14// Export function declaration separately
15function isBusinessExecutive ({ profession }) { return profession === 'business executive' }
16export default isBusinessExecutive
17
18// Export class inline
19export default class Person { /* ... */ }
20
21// Export class separately
22class Person { /* ... */ }
23export default Person

Imports

1// import named exports
2import { isGreen, isRed } from './color-tests'
3
4// import default export
5import isBlue from './color-tests'
6
7// import both default and named exports
8import isBlue, { isGreen, isRed } from './color-tests'
9
10// defaults have no specific names, just conventions
11import izBloo from './color-tests'
12
13// named exports can be explicitly renamed
14import { isGreen as izGrene } from './color-tests'

More articles from Martin Rosenberg

Shello World

Writing a Scala script

October 1st, 2018 · 5 min read

Clean Water

Make sure you drink safe water when you travel.

September 4th, 2017 · 1 min read
© 2020 Martin Rosenberg
Link to $https://github.com/MartinRosenbergLink to $https://www.linkedin.com/in/MartinBRosenberg/Link to $https://paypal.me/MartinBRosenbergLink to $https://stackoverflow.com/users/2303326/martinrosenbergLink to $https://twitter.com/Marty_Rosenberg