Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

SyntaxError: Cannot use import statement outside a module: how to fix it in Node.js

SyntaxError: Cannot use import statement outside a module means Node.js loaded a file as CommonJS and found an ES module import in it. The reverse, ReferenceError: require is not defined in ES module scope, means it loaded the file as an ES module and found require. Node.js decides by the file extension and the type field in package.json: set "type": "module", rename the file to .mjs or .cjs, or compile TypeScript with module nodenext and start the built file.

By Livops team, the people who build and run LivopsUpdated

As Node.js 24 prints it (shortened; paths vary):

(node:41) Warning: Failed to load the ES module: /app/src/index.js. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.
/app/src/index.js:1
import express from "express";
^^^^^^

SyntaxError: Cannot use import statement outside a module

And the reverse:

file:///app/src/index.js:1
const express = require("express");
                ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/app/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

This page explains the two module systems in Node.js, how Node.js decides which one a file belongs to, the reasons the error appears only after a deploy, and the fix for each. The last section shows where it surfaces on Livops.

What does the error mean?

Node.js has two module systems: CommonJS, with require() and module.exports, and ECMAScript modules (ES modules), with import and export[2]. Each file is loaded by one of them, and the syntax of the other is an error there.

  • Cannot use import statement outside a module: Node.js loaded the file as CommonJS, and it contains an import statement.
  • require is not defined in ES module scope: Node.js loaded the file as an ES module, which has no require, exports or module.exports, and no __filename or __dirname[2]. Node.js adds you can use import instead, and when the reason is "type": "module" in package.json, it names that file and suggests the .cjs extension[6]. The same happens for exports: ReferenceError: exports is not defined in ES module scope.

The fix is rarely in the line the error points at. It is in how Node.js classified the file.

How does Node.js decide which kind a file is?

In this order[1]:

File Nearest package.json Loaded as
.mjs anything ES module
.cjs anything CommonJS
.js "type": "module" ES module
.js "type": "commonjs" CommonJS
.js no type field, or no package.json at all CommonJS, unless it contains ES module syntax

The extension wins: .mjs is always an ES module and .cjs always CommonJS, whatever type says[1]. The type field applies to every .js file that has that package.json as its nearest parent[1].

The last row is syntax detection. For a .js file with no type to go by, Node.js tries CommonJS first and, if the parser finds ES module syntax (import, export, import.meta, a top-level await), runs the file again as an ES module[1]. Detection has been on by default since Node.js 22.7.0 and 20.19.0[1]; before that, such a file failed with this error. It works, but it costs time, and Node.js asks package authors to always set type[1]. It prints a MODULE_TYPELESS_PACKAGE_JSON warning that says the same.

So on a current Node.js, Cannot use import statement outside a module means the file was explicitly CommonJS: a .cjs file, or "type": "commonjs" in package.json.

Causes, most common first

1. package.json says “type”: “commonjs”

You may never have typed it: npm init writes the type field, and its default value is "commonjs"[8]. With that line, every .js file in the package is CommonJS and syntax detection does not apply[1].

Fix, if the project uses import throughout: say so in package.json.

{
  "type": "module",
  "scripts": {
    "start": "node src/index.js"
  }
}

Then every .js file under it is an ES module[1], including config files that use require or module.exports. Those now fail with the reverse error. Rename each of them to .cjs, which stays CommonJS whatever type says[1].

Fix, if only one file is different: rename that file to .mjs (an ES module) or .cjs (CommonJS), and leave type alone.

2. One file mixes import and require

A file with both import at the top and require() below it is treated as an ES module, either by "type": "module" or by syntax detection, and then require does not exist. Convert the require calls to import. Where you cannot, build a require function[4]:

import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const legacy = require("./legacy.cjs");

__dirname and __filename have replacements too: import.meta.dirname and import.meta.filename[2], added in Node.js 21.2.0 and 20.11.0[2].

import path from "node:path";
const dataDir = path.join(import.meta.dirname, "data");   // was path.join(__dirname, "data")

Relative imports in an ES module also need the file extension, ./utils.js and not ./utils[2]. Missing it is a different error, covered in Cannot find module.

3. TypeScript is compiled to the wrong module format

tsc decides whether the .js it writes uses import or require, from the module option in tsconfig.json. Two mismatches are common:

  • "module": "commonjs" with "type": "module". The output uses require and exports, and Node.js loads it as an ES module: ReferenceError: exports is not defined in ES module scope. The handbook says of commonjs for Node.js: you probably should not use it[7].
  • "module": "esnext" for a server. The output uses import. The handbook says not to use esnext for Node.js; it is meant for bundlers[7].

Fix: use nodenext (or node16, node18, node20), which the handbook calls the only correct module options for code that runs in Node.js[7]. With it, each file’s format follows the same rules Node.js uses: .mts is an ES module, .cts is CommonJS, and .ts is an ES module if the nearest package.json has "type": "module", otherwise CommonJS[7]. The emitted JavaScript gets the same format[7], so tsc and Node.js agree by construction. module: nodenext also sets moduleResolution: nodenext[7].

{
  "compilerOptions": {
    "module": "nodenext",
    "outDir": "dist"
  }
}

Under nodenext, a relative import without an extension is not supported[7]: write import { db } from "./db.js" in the .ts source.

4. The start command runs the source, not the build

The code is fine after the build, but the server starts something else: node src/index.js when src/ is written for a bundler or Babel, or a .ts file. Point the start command at what the build writes:

"scripts": {
  "build": "tsc",
  "start": "node dist/index.js"
}

About running .ts directly: Node.js strips TypeScript types by default since 23.6.0 and 22.18.0[5]. A .ts file gets its module system the same way as a .js file, so to use import it needs "type": "module"; .mts is always an ES module and .cts always CommonJS[5]. Node.js does not read tsconfig.json[5], and it refuses TypeScript files inside node_modules[5]. Older versions do not run .ts files by default. A build step is the predictable choice for a server.

5. The server runs a different Node.js version

Three behaviours in this area depend on the version:

  • syntax detection for .js files without type: on by default from 22.7.0 and 20.19.0[1];
  • running .ts files: by default from 23.6.0 and 22.18.0[5];
  • require() of an ES module from CommonJS: no flag needed from 22.12.0 and 20.19.0[3]. It loads only modules without top-level await; for those it throws ERR_REQUIRE_ASYNC_MODULE, and you load them with import() instead[3].

A project that works on your Node.js 24 can fail on an older Node.js on the server. Check node --version in both places, and pin the version in the project.

In Jest tests

If the error comes from Jest rather than from your server: Jest’s support for ES modules is experimental[9]. To use it, turn off code transforms with transform: {} (or make your transformer emit ES modules) and run Jest under node --experimental-vm-modules[9]:

NODE_OPTIONS="$NODE_OPTIONS --experimental-vm-modules" npx jest

How to confirm the fix locally

Run what the server runs, from a fresh clone, with the server’s Node.js version:

git clone <your repo> /tmp/check && cd /tmp/check
node --version
node -p "require('./package.json').type"   # module, commonjs, or undefined
npm ci && npm run build
npm start

To try another Node.js version without installing it:

docker run --rm -v "$PWD":/app -w /app node:22 sh -c "npm ci && npm run build && npm start"

On Livops

  • Where it shows. The build passes, the app stops right after it starts, and the deploy fails as start_failed. The Logs page shows the app’s last words, the SyntaxError among them, often with a Tip: line under it. A web app’s previous version keeps running; a bot’s previous version is stopped first, so the bot is down until a deploy succeeds. See The app did not start.

  • The start command. Set it in Settings → Start. In livops.json, start is applied when the project is created; after that it is changed in the project’s settings. A Procfile at the project root works too: web: for a site or an API, worker: for a bot.

    {
      "build": "npm run build",
      "start": "node dist/index.js"
    }
  • Without a start command, Livops looks for the start script in package.json, then the main field, then index.js, server.js, app.js, main.js. For TypeScript, its docs say what cause 4 says: build first and start the built file, for example node dist/main.js. See No start command.

  • Node.js versions. Livops has Node.js 22 and 24. It reads .nvmrc and .node-version, and devEngines.runtime.version in package.json can ask for 22 or 24. See Install failed.

A start that fails with Cannot find module instead is in Error: Cannot find module, and running a Node.js server in production in Node.js hosting.

Questions

Should I add "type": "module" or rename the file to .mjs?

Add "type": "module" when the whole project uses import and export: every .js file under that package.json becomes an ES module. Rename one file to .mjs, or to .cjs, when only that file is different. The extension wins over the type field.

Why does it work on my machine but not on the server?

Usually the Node.js version or the start command differs. Node.js 22.7 and later, and 20.19 and later, detect ES module syntax in a .js file when package.json has no type field; older versions do not. And the server may start a source file your machine never runs directly, such as src/index.js instead of the built dist/index.js.

What does ReferenceError require is not defined in ES module scope mean?

The reverse problem. Node.js loaded the file as an ES module, where require, exports, module.exports, __filename and __dirname do not exist. Replace require with import, rename the file to .cjs to keep it CommonJS, or build a require function with createRequire from node:module.

How do I get __dirname in an ES module?

Use import.meta.dirname and import.meta.filename. They were added in Node.js 21.2 and 20.11, so Node.js 22 and 24 have them, and they work only for modules loaded from files.

Which tsconfig module setting should a Node.js app use?

nodenext, or node16, node18 or node20. The TypeScript handbook calls them the only correct module options for code that runs in Node.js. Each .ts file is then emitted as an ES module when package.json says "type": "module", and as CommonJS otherwise. esnext is meant for bundlers, not for Node.js.

Can I start a .ts file with node directly?

In Node.js 22.18 and later, and 23.6 and later, type stripping is on by default, so node src/index.ts runs. The module format is decided as for a .js file, tsconfig.json is ignored, and import paths need their .ts extension. A build with tsc and a start command that runs the built file is the safer choice for a server.

Where do I set the start command on Livops?

In the project's Settings, under Start, or in a Procfile at the project root. The start field of livops.json is applied only when the project is created; after that, change it in the settings.

Sources

  1. Node.js Docs — Modules: Packages (nodejs.org). Checked .
  2. Node.js Docs — Modules: ECMAScript modules (nodejs.org). Checked .
  3. Node.js Docs — Modules: CommonJS modules (nodejs.org). Checked .
  4. Node.js Docs — Modules: node:module API (nodejs.org). Checked .
  5. Node.js Docs — Modules: TypeScript (nodejs.org). Checked .
  6. Node.js source — lib/internal/modules/esm/module_job.js (github.com). Checked .
  7. TypeScript Handbook — Modules: Reference (typescriptlang.org). Checked .
  8. npm Docs — config (docs.npmjs.com). Checked .
  9. Jest Docs — ECMAScript Modules (jestjs.io). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your Node app

Got a question? — @livops_uz