import

Loads values exported from another ES module: functions, classes, constants, or a whole module.

On this page

Example

#
JavaScript
// utils.js
export function formatPoints(points) {
  return `${points} pts`
}

// main.js
import { formatPoints } from './utils.js'

console.log(formatPoints(120))
Result
120 pts

Definition and usage

#

The import statement pulls in whatever another file made available with export. Modules let you split code into small files with a clear job, and each file gets its own scope, so variables don’t clutter the global namespace.

You import named exports in braces, under the same name (import { formatPoints } from "./utils.js"), optionally renaming it with as. You import the default export without braces, under any name you like. The form import * as utils collects every export into a single object.

import declarations must sit at the top level of a file, and imported modules run before the rest of the code starts. When a module should only load on demand, use the import() function, which returns a promise. In a browser, a script with import statements needs a type="module" attribute.

Syntax

#
Syntax
import defaultExport from './module.js'
import { name1, name2 as alias } from './module.js'
import defaultExport, { name } from './module.js'
import * as namespace from './module.js'
import './module.js'
const module = await import('./module.js')

More examples

#
Default export and renaming
JavaScript
// student.js
export default class Student {
  constructor(name) {
    this.name = name
  }
}

export const MAX_LEVEL = 50

// main.js
import Student, { MAX_LEVEL as limit } from './student.js'

const mia = new Student('Mia')
console.log(mia.name, limit)
Result
Mia 50
Importing the whole module
JavaScript
// math.js
export const add = (a, b) => a + b
export const multiply = (a, b) => a * b

// main.js
import * as math from './math.js'

console.log(math.add(2, 3))
console.log(math.multiply(4, 5))
Result
5
20
Dynamic import()
JavaScript
const button = document.querySelector('#stats')

button.addEventListener('click', async () => {
  const { drawChart } = await import('./chart.js')
  drawChart()
})

The chart code is only fetched after the click. The page loads faster, because it doesn’t download everything up front.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • In a browser, give the full path with the extension, e.g. ./utils.js. Leaving the extension out usually only works in tools like Vite or webpack.
  • Imported names are read-only. You can’t assign them a new value, but when the source module changes its own variable, you’ll see the new value.
  • Modules opened straight from disk (file://) usually don’t work, due to browser security rules. Run the project on a local server, for example through Vite.

Related entries

#

Spotted a mistake or missing an example? Write to us.