How to use import in Node.js

By

Published · Updated

Tagged: Node.js

Learn how to use import instead of require in Node.js by adding type module to your package.json, so you can switch to clean ES modules import syntax.

To use import in Node.js, add "type": "module" to your package.json file. That single line switches your project from CommonJS to ES modules.

Using Node.js you traditionally load modules with require():

const fs = require('fs')

That’s the CommonJS module system, the one Node.js was born with.

import is the ES modules syntax, the official JavaScript standard. It’s what you use in the browser and in every modern frontend framework. Using it in Node.js too means one syntax everywhere:

import fs from 'fs'

Enable ES modules in package.json

Node.js treats .js files as CommonJS by default. Since Node.js 22.7 it detects import syntax in a .js file with no "type" set and runs it as an ES module anyway, but it prints a warning and the detection costs some performance. To make it explicit, go in the package.json file and add "type": "module", like this:

{
  "name": "projectname",
  "type": "module",
  "version": "1.0.0",
  ...the rest of your file
}

That’s it. Every .js file in the project now uses ES modules, and import works:

import fs from 'fs'

You can also use named imports to pick specific functions:

import { readFile } from 'node:fs/promises'

If you can’t touch package.json, there’s an alternative: name the file with the .mjs extension. Node.js always treats .mjs files as ES modules, no configuration needed.

Watch out: require() stops working

The switch goes both ways. Once "type": "module" is set, calling require() in a .js file throws:

ReferenceError: require is not defined in ES module scope, you can use import instead

So you can’t mix the two syntaxes in the same file. Convert every require() in the project to import. If one old script really needs to stay CommonJS, rename it to .cjs and Node.js will treat it as CommonJS again.

One more thing that trips people up: when you import your own files, ES modules require the file extension.

import { calculateTotal } from './cart.js'

With CommonJS you could write require('./cart') and Node.js would guess. With import, leaving out .js gives you a “module not found” error.

Also gone in ES modules: the __dirname and __filename variables. They only exist in CommonJS. Using one throws ReferenceError: __dirname is not defined in ES module scope. Use import.meta.dirname and import.meta.filename instead (Node.js 20.11 or newer). See ES modules for more on how they work.

Export from your own files

import pairs with export. You can have one default export per file, and as many named exports as you want:

// cart.js
export function calculateTotal(items) {
  return items.reduce((sum, price) => sum + price, 0)
}

export default function formatPrice(n) {
  return `$${n.toFixed(2)}`
}

The default export has no braces when you import it, and you can give it any name. Named exports go in braces and must match the exported name:

import formatPrice, { calculateTotal } from './cart.js'

console.log(formatPrice(calculateTotal([1, 2.5]))) // $3.50

This replaces module.exports = ... and exports.something = ... from CommonJS.

Import a JSON file

With require() you could load a JSON file directly. With import you need to say it’s JSON, using an import attribute:

import config from './config.json' with { type: 'json' }

console.log(config.port)

Leave out with { type: 'json' } and you get TypeError [ERR_IMPORT_ATTRIBUTE_MISSING]: Module ".../config.json" needs an import attribute of "type: json". The JSON is only available as a default export, so import { port } from './config.json' doesn’t work.

If you want to read the file at runtime instead, for example because it changes, use readFile from node:fs/promises and JSON.parse().

Import CommonJS packages

Most npm packages still work after you switch, even the ones written in CommonJS. Node.js gives you their module.exports object as the default export:

import express from 'express'

Named imports from a CommonJS module only work when Node.js can detect the names by reading the code, which mostly means the module uses exports.name = .... When it can’t, you get an error like this:

SyntaxError: Named export 'greet' not found. The requested module './legacy.cjs' is a CommonJS module, which may not support all module.exports as named exports.

The fix is in the error message itself. Import the default and destructure it:

import pkg from './legacy.cjs'
const { greet } = pkg

If you need require() for something specific, you can still create one inside an ES module:

import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)

const config = require('./config.json')

Load modules on demand with import()

import statements must be at the top level of the file. You can’t put one inside an if or a function. For that there’s import(), which works like a function and returns a promise:

if (process.env.NODE_ENV === 'development') {
  const { default: formatPrice } = await import('./cart.js')
  console.log(formatPrice(3)) // $3.00
}

The default export is in the default property. The await here works without an async function because ES modules support top-level await. import() also works in CommonJS files, so it’s the way an old .cjs file can load an ES module.

Can CommonJS require() an ES module?

Yes, in recent versions. Since Node.js 22.12 (and 20.19), require() can load an ES module without any flag:

// old.cjs
const { calculateTotal } = require('./cart.js')

There’s one exception. If the ES module, or anything it imports, uses top-level await, require() throws ERR_REQUIRE_ASYNC_MODULE. Use import() for those.

Want me to talk about your product? You can sponsor this site.

Related posts about node: