Skip to content
Latchkey

Node "SyntaxError: Cannot use import statement outside a module" in CI

Node parsed the file as CommonJS, where import is not valid syntax. A .js file is CommonJS unless the nearest package.json sets "type": "module", or the file is renamed to .mjs.

What this error means

Running a script with top-level import fails immediately with "SyntaxError: Cannot use import statement outside a module" at the first import line.

node
import express from 'express';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)

Common causes

The file is treated as CommonJS

A .js file with no "type": "module" in the nearest package.json is CommonJS, so import/export syntax is a parse error.

A tool ran raw .ts/.jsx through Node without transpiling

Node received source with import that a bundler or loader was supposed to compile, but the build step was skipped in CI.

How to fix it

Declare the package as ESM

Add "type": "module" so Node parses .js files as ES modules and import is valid.

package.json
{
  "type": "module"
}

Or rename the entry to .mjs

A .mjs file is always parsed as ESM regardless of package.json, which is useful for a single script.

Terminal
node ./scripts/build.mjs

How to prevent it

  • Decide CommonJS vs ESM per package and keep it consistent.
  • Run the build step in CI so transpiled output, not raw source, reaches Node.
  • Use .mjs/.cjs extensions to be explicit when mixing module systems.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →