CalcSnippets Search
Node.js 2 min read

`Cannot use import statement outside a module` Usually Means Your Node Project Is Half in ESM, Half in CommonJS, and Acting Surprised About the Divorce

A practical guide to fixing Node ESM/CommonJS import errors by checking `type`, file extensions, transpiler output, and runtime entrypoints instead of mixing module systems accidentally.

Why this error matters: this is one of the clearest signals that your runtime expectations and your file/module configuration do not agree, even if your editor keeps highlighting everything like it is fine.

A very common Node failure still looks like:

SyntaxError: Cannot use import statement outside a module

This usually means one of two things:

  1. Node is treating the file as CommonJS
  2. the code inside it is written as ESM

That mismatch is the real issue.

First check your package boundary

Look at package.json:

{
  "type": "module"
}

If type is absent, .js files are treated as CommonJS by default in many Node setups.

So this file:

import express from 'express';

will fail unless:

  1. the package is marked "type": "module"
  2. or the file uses .mjs

Clean ways to fix it

Option 1: Go ESM on purpose

Set:

{
  "type": "module"
}

Then keep using import and export.

Option 2: Stay CommonJS on purpose

Rewrite the entrypoint:

const express = require('express');

and use module.exports or exports.

Option 3: Use .mjs for ESM files

If you do not want to change package-wide behavior, rename the entry file:

server.mjs

and run:

node server.mjs

Transpiler trap

TypeScript, Babel, or bundlers may emit one module format while your runtime expects another. So if source code looks modern but emitted output is CommonJS, the file you actually run may not match the file you think matters.

Inspect the real execution target:

cat package.json
node -p "require('./package.json').type"

and check whether npm start runs source or build output.

If the problem happens in tests or scripts

Sometimes the app itself works, but:

  • Jest
  • ts-node
  • old build scripts
  • one-off CLI files

still assume CommonJS.

So the issue may be localized to one toolchain edge, not the whole app.

Final recommendation

Pick one module strategy intentionally for the file you are running. Either mark the package as ESM, rename the file to .mjs, or rewrite the entrypoint to CommonJS. The error is usually configuration truth, not JavaScript hostility.

Sources

Keep reading

Related guides