Skip to content
Latchkey

Node "Cannot use import statement outside a module" in CI - Fix It

This SyntaxError means Node parsed a file as CommonJS but the file uses ES import syntax. The runtime never reaches your logic; parsing fails first.

What this error means

A node command throws SyntaxError: Cannot use import statement outside a module at the first import line. The file uses import/export but Node is loading it as CommonJS.

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

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

Common causes

No "type": "module" in package.json

A .js file with import syntax is parsed as CommonJS unless the nearest package.json declares type module.

Running uncompiled TypeScript or JSX directly

Node runs raw source that should have passed through a build or loader (tsc, tsx, babel) but did not.

How to fix it

Declare the package as ESM

  1. Add "type": "module" to package.json so .js files are treated as ES modules.
  2. Make sure your require() calls are converted to import or moved to .cjs files.
package.json
{
  "type": "module"
}

Transpile before running

  1. Run the build (tsc, esbuild, babel) so the emitted CommonJS no longer uses import syntax.
  2. Execute the compiled output instead of the source.
GitHub Actions
- run: npm run build
- run: node dist/server.js

How to prevent it

  • Pick one module system per package, set the matching "type" field, and run compiled output in CI rather than raw source that depends on a loader being present.

Related guides

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