How to use import in Node.js

By

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. To change that, 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. If your code uses them, you’ll need to derive the same information from import.meta.url after the switch.

Tagged: Node.js · All topics
~~~

Related posts about node: