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'34// Export a function declaration inline.5export function isPink (color) { return color === 'pink' }67// Export a class inline.8export class LittleBox { /* ... */ }910// Export at the bottom.11const blue = 'blue'12function yellow () { return 'yellow' }13class Hillside {}1415export { 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 debugging2// because the variable has no name for stack traces.3export default ({ profession }) => profession === 'doctor'45// Export variable separately.6const isDoctor = ({ profession }) => profession === 'doctor'7export default isDoctor89// Export function declaration inline. This causes the same10// problems if you don't name the function.11export default function ({ profession }) { return profession === 'lawyer' }12export default function isLawyer ({ profession }) { return profession === 'lawyer' }1314// Export function declaration separately15function isBusinessExecutive ({ profession }) { return profession === 'business executive' }16export default isBusinessExecutive1718// Export class inline19export default class Person { /* ... */ }2021// Export class separately22class Person { /* ... */ }23export default Person
Imports
1// import named exports2import { isGreen, isRed } from './color-tests'34// import default export5import isBlue from './color-tests'67// import both default and named exports8import isBlue, { isGreen, isRed } from './color-tests'910// defaults have no specific names, just conventions11import izBloo from './color-tests'1213// named exports can be explicitly renamed14import { isGreen as izGrene } from './color-tests'