Skip to content
Latchkey

TypeORM "Cannot use import statement outside a module" in CI

The TypeORM CLI loaded a .ts DataSource or migration with plain Node, which cannot parse import syntax. You need a TypeScript loader (ts-node) or to run the compiled JavaScript instead.

What this error means

typeorm migration:run (or migration:generate) fails with "SyntaxError: Cannot use import statement outside a module" pointing at your TypeScript data source or migration file.

typeorm output
import { DataSource } from "typeorm";
^^^^^^

SyntaxError: Cannot use import statement outside a module

Common causes

Running TS files with Node and no loader

The CLI was invoked against .ts files without ts-node, so Node tries to execute TypeScript directly and chokes on import.

Module/CommonJS mismatch in the loader config

A misconfigured tsconfig or missing ts-node registration leaves the file parsed as CommonJS while it uses ESM import syntax.

How to fix it

Run the CLI through ts-node

Register ts-node so the TypeScript DataSource and migrations load correctly.

Terminal
npx typeorm-ts-node-commonjs migration:run -d src/data-source.ts

Or compile first and run the JS

  1. Build the project so migrations and the DataSource become .js.
  2. Point the CLI at the compiled DataSource.
  3. Ensure the migrations glob targets the built output.
Terminal
npm run build
npx typeorm migration:run -d dist/data-source.js

How to prevent it

  • Use the ts-node TypeORM entrypoint when running TS sources.
  • Or build before migrating and point the CLI at dist.
  • Keep the migrations glob consistent with TS vs compiled output.

Frequently asked questions

What causes "TypeORM "Cannot use import statement""?
The CLI was invoked against .ts files without ts-node, so Node tries to execute TypeScript directly and chokes on import.
How do I fix TypeORM "Cannot use import statement"?
Register ts-node so the TypeScript DataSource and migrations load correctly.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card