Fix "Cannot Use Import Statement Outside a Module" in TypeScript


SyntaxError: Cannot use import statement outside a module means a runtime loaded a file with import syntax as CommonJS. In TypeScript projects in 2026, that usually happens in one of four places: Jest, the browser, a package explicitly marked "type": "commonjs", or an old Node.js version.

Today we’re going nerdy on a whole different topic. This was something that plagued me for a few years, as I was still getting comfortable with Typescript back in ~2020.

Admittedly, that list is shorter than it used to be. Most guides for this error were written before Node.js learned to sort out ESM on its own, and they still tell you to restructure your project. Often you don’t need to.

This article covers what changed in Node.js, the cases where the error still shows up, and the fix for each one. Every config and command below was tested on Node.js 24.22, TypeScript 6.0 and 7.0, and Jest 30.5. Its possible that there are some combination(s) of these tools that may break in different ways, as I just put these together for reproduction purposes.

Key Takeaways

  • On Node.js 22.12+ (and 20.19+), a .js file with import and no "type" field runs anyway. Node detects the ESM syntax and prints a warning instead of crashing.
  • Node.js still throws the error when the nearest package.json says "type": "commonjs", or the file is .cjs / .cts.
  • require() of an ESM-only package like chalk@5 now works on Node 22.12+, as long as the package doesn’t use top-level await.
  • Jest is the most common source today, because by default it doesn’t transform code in node_modules. Fix it with transformIgnorePatterns.
  • "moduleResolution": "node" is deprecated in TypeScript 6 and removed in TypeScript 7. For CommonJS output, use "module": "nodenext" without "type": "module".

Why “Cannot Use Import Statement Outside a Module” Happens

So why does this happen? Its a little nerdy, but Node.js has two module systems. Aaand they’re different. A module system is essentially a way to load files. That’s the easy way to think about it. In reality it’s also how code is organized, exposed (and exported), evaluated and shared between files. CommonJS uses require() and module.exports. ESM uses import and export. Before running a file, Node.js has to decide which one it’s looking at. The Node.js docs on determining the module system list the rules:

  1. File extension: .mjs and .mts are always ESM. .cjs and .cts are always CommonJS.
  2. "type" in the nearest package.json: "module" makes .js files ESM, and "commonjs" makes them CommonJS.
  3. No "type" field: Older Node.js versions defaulted to CommonJS. Newer ones inspect the syntax first.

The error fires when step 1 or 2 says “CommonJS” and the file contains import. TypeScript makes this mismatch very easy to create. Because most often, you write import in your source code no matter what you compile to, so the source code tells you nothing about what the runtime will see. Effectively you are flying blind, even with Typescript.

What Changed in Node.js 22 and 24

Three features moved out of experimental status between 2024 and 2025. Together they remove most of the old causes:

ScenarioNode.js 18Node.js 22.12+ / 24
.js with import, no "type" field❌ Error✅ Runs, with a MODULE_TYPELESS_PACKAGE_JSON warning
.js with import, "type": "commonjs"❌ Error❌ Error
require() of an ESM-only package❌ ERR_REQUIRE_ESM✅ Works, unless the package uses top-level await
node index.ts directly❌ Unknown file extension✅ Runs (type stripping)

The first row is syntax detection. When a file has no explicit type, Node.js tries CommonJS, sees import, and re-parses the file as ESM. Here’s what Node 24 prints instead of an error:

Warning: Module type of file:///app/index.js is not specified and it doesn't parse as CommonJS.
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
To eliminate this warning, add "type": "module" to /app/package.json.

The warning is worth acting on, because detection parses the file twice. Still, it’s a warning rather than a crash, which changes what you need to do.

The third row is require(esm).

Node.js 20 is end-of-life as of April 2026, so a current LTS (24 or 26) has all three features. If you’re on Node.js 18 or older and see this error, upgrading Node.js is the fix with the most leverage. It removes a whole class of module problems instead of patching one.

Fix 1: Node.js Is Told Your File Is CommonJS

On a modern Node.js version, the error from Node itself almost always means something explicitly declared CommonJS. Here’s a minimal reproduction:

{
  "name": "my-app",
  "type": "commonjs"
}
// index.ts
import { sep } from "node:path";
console.log(sep);
$ node index.ts
SyntaxError: Cannot use import statement outside a module

Detection doesn’t run here, because you told Node.js what to expect. You have three options:

  • Switch the package to ESM: Change "type" to "module". Then line up your tsconfig as described in enabling ESM in TypeScript without the headaches.
  • Make one file ESM: Rename it to .mts (or .mjs for compiled output). The extension overrides the "type" field, which works well for a single script in a CommonJS package.
  • Compile to CommonJS: Keep "type": "commonjs" and let TypeScript turn import into require(). See Fix 2.

Also check for a package.json you forgot about. Node.js uses the nearest one walking up from the file, so a stray package.json in dist/ or a monorepo subfolder can override the root one.

Fix 2: Compile TypeScript to CommonJS Correctly

If your project is CommonJS and should stay that way, make TypeScript emit CommonJS. Older guides recommend this:

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node"
  }
}

That config no longer works. TypeScript 6 rejects it with TS5107: Option 'moduleResolution=node10' is deprecated, and TypeScript 7 removes it (TS5108). The current way is nodenext:

{
  "compilerOptions": {
    "module": "nodenext",
    "target": "es2022",
    "rootDir": "src",
    "outDir": "dist",
    "esModuleInterop": true
  }
}

With "module": "nodenext", TypeScript reads the same "type" field that Node.js reads. If package.json has no "type": "module", it emits require() calls. You keep writing import in source, and TypeScript translates it.

This setup has two benefits over the old one. TypeScript and Node.js can’t disagree about the module format, because they read the same field. And when you later flip to "type": "module", the tsconfig doesn’t change.

TypeScript 6 and 7 also require an explicit rootDir when it can’t be inferred. That’s why it’s in the example.

When CommonJS Is the Right Call

ESM is where the ecosystem is going. But since require(esm) landed, the cost of staying on CommonJS has dropped a lot. ESM-only dependencies, the main reason to migrate a few years ago, now load from CommonJS on Node 22.12+.

Stay on CommonJS when you have a large codebase that works, a Jest suite built on CommonJS mocking, or a deadline. Migrate when you want top-level await or you’re starting fresh. My guide to converting a TypeScript project from CJS to ESM covers what the migration costs.

Fix 3: “Cannot Use Import Statement Outside a Module” in Jest

Jest is where most people hit this error today. Your app runs fine, but tests fail on an import inside node_modules.

The cause is Jest’s own module system. Jest doesn’t use Node’s loader. It transforms files itself and runs them as CommonJS. By default, it skips transforming anything in node_modules. An ESM-only dependency reaches the CommonJS runtime untouched, and Jest fails.

Older Jest versions report this as Jest encountered an unexpected token followed by SyntaxError: Cannot use import statement outside a module. In Jest 30.5, the same failure looks like this:

Must use import to load ES Module: /app/node_modules/some-esm-package/index.js

The file contains ESM syntax (import/export) that could not be executed as CommonJS.

Same cause, different wording, so it’s worth knowing both.

Fix: Let Jest Transform the ESM Package

Tell Jest which packages to transform with transformIgnorePatterns. Since the pattern lists what to skip, you write a negative lookahead for the packages you want included:

// jest.config.cjs
module.exports = {
  testEnvironment: "node",
  transform: {
    "^.+\\.[tj]sx?$": ["ts-jest", { tsconfig: "tsconfig.jest.json" }],
  },
  transformIgnorePatterns: [
    "/node_modules/(?!(\\.pnpm/)?(chalk|some-esm-package)[@/])",
  ],
  moduleNameMapper: {
    "^(\\.{1,2}/.*)\\.js$": "$1",
  },
};
// tsconfig.jest.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": { "allowJs": true }
}

Each piece has a job:

  • transform matches .js as well as .ts: The dependency is JavaScript, so ts-jest has to handle .js files too.
  • allowJs: Without it, ts-jest won’t compile the dependency’s JavaScript.
  • (\\.pnpm/)? in the pattern: pnpm stores packages under node_modules/.pnpm/name@version/. Without this, the pattern misses them.
  • moduleNameMapper: If you use nodenext, your relative imports end in .js (see fixing ERR_MODULE_NOT_FOUND in TypeScript ESM). Jest’s resolver doesn’t map ./hi.js back to ./hi.ts, so this does.

The cost is speed. Every package you add gets compiled on each cold run. Keep the list to the packages that actually need it.

Alternative: Node 24.9+ and Native ESM in Jest

Recent Jest 30 releases can load ESM dependencies natively on Node 24.9 or later, but only with Node’s VM modules flag:

NODE_OPTIONS=--experimental-vm-modules npx jest

In my test, this made an untransformed ESM dependency load without any transformIgnorePatterns. The flag is still experimental, though, and it changes how mocking behaves. I personally rarely use these flags, especially not in production, though its nice to know and experiment with. I recommend using the transform approach.

ts-jest and TypeScript 7

If you’ve upgraded to TypeScript 7, ts-jest fails with The TypeScript compiler "typescript" (version 7.0.2) does not expose the JavaScript compiler API. TypeScript 7 is the Go-based compiler, and it doesn’t ship the JavaScript API that ts-jest calls. Follow the alias instructions in the error message, or keep typescript@6 installed for ts-jest.

Hopefully this gets resolved with Typescript 7.1 any day now, when the tooling can utilize TS APIs.

… Or Use Vitest!

If you’re not tied to Jest, Vitest avoids this problem. It runs on Vite’s ESM pipeline and lets Node.js load dependencies natively, so ESM-only packages just work. For a new project, that’s the simpler default.

In general I really like vitest, and I highly recommend it. At work, where we have an old legacy frontend using parts react, parts angular, vitest nicely works through both.

Fix 4: The Browser Version of the Error

In a browser, the error reads Uncaught SyntaxError: Cannot use import statement outside a module. The cause is the same in a different place: a classic <script> tag doesn’t allow import.

<!-- Fails -->
<script src="/main.js"></script>

<!-- Works -->
<script type="module" src="/main.js"></script>

type="module" tells the browser to load the file as ESM, as described in MDN’s guide to JavaScript modules. Two follow-on problems are common. Modules don’t load over file://, so you need a local server. And bare imports like import x from "lodash" don’t resolve in the browser without an import map or a bundler.

In TypeScript projects, this usually means tsc output is being served directly. If you’re using a bundler like Vite, it adds type="module" for you. If you see this error with a bundler, check that the HTML points at the bundled output and not at your src/.

Fix 5: Running TypeScript Directly in Development

Node.js Runs TypeScript Natively

Node.js 22.18+ and 23.6+ run .ts files directly with type stripping. It removes type annotations and runs what’s left, with no compile step:

node src/index.ts

Module rules are the same as for .js: .mts is always ESM, .cts is always CommonJS, and .ts follows "type" or syntax detection. So the "type": "commonjs" case from Fix 1 applies here too.

Type stripping has limits. It won’t run syntax that needs code generation, like enum or namespace, without an extra flag. Setting "erasableSyntaxOnly": true in your tsconfig makes TypeScript flag those constructs up front.

This approach has been somewhat enjoyable and this is honestly a flag I use from time to time. More often though, I find myself simply defaulting to using bun, which I always keep installed on my system(s).

tsx and ts-node

tsx is still useful when you need full TypeScript syntax or a watch mode with its own resolution. It compiles with esbuild before Node.js sees the code, so the module format mostly stops mattering.

ts-node is the tool older answers recommend, and it’s also the source of much of this error’s history. The ESM issue on its repository is one of its longest threads. I was a heavy ts-node user for years, and quite happy with it. It seems to work best with a variety of dependencies, that other tools just doesn’t. But again, now I mostly use bun.

Bun

Bun runs TypeScript natively and accepts both import and require in the same file, so this error rarely comes up there. The trade-off is that Bun isn’t Node.js. Check that your production runtime matches what you develop on.

Frequently Asked Questions

Why does my TypeScript code run but my Jest tests fail with this error?

Jest doesn’t use Node’s module loader. It transforms files itself and skips node_modules by default, so an ESM-only dependency reaches its CommonJS runtime untouched. Add the package to transformIgnorePatterns, as in Fix 3.

Do I need “type”: “module” in package.json?

Not to make the error go away on Node.js 22.12+. Syntax detection runs ESM files without it. Add it anyway if your project is ESM, because it removes the warning, avoids double parsing, and makes TypeScript’s nodenext emit ESM.

Can I require() an ESM-only package in a CommonJS project?

Yes, on Node.js 22.12+ and 20.19+, as long as the package’s module graph doesn’t use top-level await. On older versions, use dynamic await import("package") or pin a major version that still ships CommonJS.

Is “Cannot use import statement outside a module” a TypeScript compiler error?

No. tsc happily compiles import statements. The error comes from whatever runs the output: Node.js, Jest, or a browser. That’s why you have to fix it in the runtime configuration or the emit settings, not in the code.

What’s the difference between this error and ERR_REQUIRE_ESM?

They’re opposite mismatches. “Cannot use import statement” means ESM code was loaded as CommonJS. ERR_REQUIRE_ESM means CommonJS code called require() on an ESM file, which modern Node.js mostly allows now.

Conclusion

The cannot use import statement outside a module error in TypeScript always means the same thing: a file with ESM syntax was loaded as CommonJS. What’s changed is where that still happens.

  • Node.js 22.12+: Detects ESM on its own. The error only appears when something explicitly says CommonJS.
  • TypeScript: Use "module": "nodenext" and let "type" in package.json decide the output format.
  • Jest: The most common source today. Use transformIgnorePatterns, or consider Vitest.
  • Browser: Add type="module" to the script tag.

Before changing your project’s module system, check which runtime is actually throwing the error and which version it is. Often the right fix is a single line, or a Node.js upgrade.

If you’ve decided to go ESM, the full CJS-to-ESM migration guide walks through the rest.