This error usually means one thing: the file is being executed as CommonJS, but it contains ES module syntax.
SyntaxError: Cannot use import statement outside a module
The fix depends on whether your project should use ES modules or CommonJS. Do not randomly change every config file. Pick one module system and make Node, TypeScript, and your package settings agree.
Quick answer
If you use import, make Node treat the file as an ES module:
{
"type": "module"
}
If you use CommonJS, write CommonJS imports:
const express = require("express");
If you are using TypeScript, do not run .ts files directly with plain node. Compile first or use a TypeScript-aware runner.
quick diagnosis
If your code uses this:
import express from "express";
Node needs to treat the file as an ES module.
If your project uses this:
const express = require("express");
Node is using CommonJS.
The error happens when those worlds are mixed.
fix 1: use ES modules
If you want to keep import, add this to package.json:
{
"type": "module"
}
Then run your file normally:
node index.js
For TypeScript, use ESM-aware settings:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true
}
}
This tells TypeScript to follow Node’s modern module behavior.
fix 2: use CommonJS
If you do not want ESM, rewrite imports:
const express = require("express");
And export like this:
module.exports = app;
For TypeScript output, CommonJS looks like:
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES2020"
}
}
This is still common in older Node projects.
fix 3: do not run TypeScript directly with node
This fails:
node src/index.ts
Node does not run TypeScript by default. Use a runner or compile first.
For development:
npx tsx src/index.ts
For production:
npx tsc
node dist/index.js
If you use tsx, still keep your package.json and tsconfig.json consistent.
check file extensions
Node uses file extensions as module signals too:
.mjsis treated as ESM..cjsis treated as CommonJS..jsdepends on"type"inpackage.json.
If one file must stay CommonJS inside an ESM project, use .cjs.
the clean rule
Use this combination for modern Node ESM:
{
"type": "module"
}
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext"
}
}
Use this combination for CommonJS:
{
"type": "commonjs"
}
{
"compilerOptions": {
"module": "CommonJS"
}
}
The error is not fixed by memorizing one magic line. It is fixed by making the runtime and compiler agree.
Discussion
What would you try, change, or challenge after reading this guide? Specific results and errors help the next reader.
Comments will load as you reach this section.