Javascript imports and exports

Functions, objects and primitive values can be exported from a module. A module can have many named exports and one default export, ES6 favours a default export per module with additional helper functions exposed as named exports. Exports can be marked ‘in-line’ or separately where the practise generally is to export at the end of the file. Exports can be aliased with ‘as’ and writing export default baz is equivalent to export { baz as default }.

//lib.js
function myFoo() {
  return 'stuff'
}

const bar = 'more stuff'

const baz = 'default stuff'

export { baz as default, myFoo as foo, bar }

Functions, objects and primitive values can be imported from modules. Default exports need to be provided with a name, named exports can be aliased.

// lib.test.js
import theDefault, { foo, bar as myBar } from './lib'

it('imports the default', () => {
  expect(theDefault).toEqual('default stuff')
})

it('imports myBar', () => {
  expect(myBar).toEqual('more stuff')
})

it('imports foo', () => {
  expect(foo()).toEqual('stuff')
})

If you have a folder of related modules a useful pattern is to create an index.js in the folder and export functions from related modules from in it.

// sub/lib1.js
function func1() {
  return 'hi from lib1'
}

export { func1 as default }
// sub/index.js
export { default as lib1 } from './lib1'
export { default as lib2 } from './lib2'
// sub.test.js
import { lib1, lib2 } from './sub'

it('imports lib1 from a subfolder', () => {
  expect(lib1()).toEqual('hi from lib1')
})

There are many more ways to import / export modules. These are just my preferences and, as with most style choices, consistency is important.

A more comprehensive guide to import and export is available on MDN.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.