JavaScript Modules

JavaScript Modules (import/export)

JavaScript, before 2015, had no language-level module syntax. But as JS applications became more and more complex, the need to split code into multiple files (or modules) became apparent. Node.js adopted the CommonJS module system and still uses it today. JavaScript's native module system was standardised in 2015 and is now supported by all major browsers and Node.js.

Default Exports

components/header.js

const renderHeader = () => {
  // ...
}

export default renderHeader

initialise.js

import renderHeader from './components/header.js'

Named Exports

components/auth.js

const login = () => {
  // ...
}

export { login }

initialise.js

import { login } from './components/auth.js'

Multiple Named Exports

components/auth.js

const login = () => {
  // ...
}

const logout = () => {
  // ...
}

export { login, logout }

initialise.js

import { login, logout } from './components/auth.js'

Using Modules Client-Side

Instead of adding multiple script tags, choose an entry point (e.g. initialise.js) and include that in a script tag with a type attribute of "module":

<script type="module" defer src="js/initialise.js"></script>

You can then use import/export in your JS files.

initialise.js

import renderHeader from './components/header.js'

renderHeader()

Last updated