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 systemarrow-up-right 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

Multiple Named Exports

components/auth.js

initialise.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":

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

initialise.js

Last updated