Typescript: Cannot use import statement outside a module

Solve the common TypeScript error "Cannot use import statement outside a module" by configuring ES modules, using .mjs, and updating tsconfig settings.

Summarize with AI

Not enough time? get the key points instantly.

This error occurs when TypeScript tries to use import in a non-module file. Fix it by enabling “module” and “type”: “module” in your config.

Problem

When you run a TypeScript or JavaScript file, you get this error:
SyntaxError: Cannot use import statement outside a module
This happens when Node.js doesn’t recognize your file as a module.

Solution

Follow these steps:

Step 1: ES Module Configuration

Make sure your package.json has:

json

“type”: “module”

Step 2: .mjs File Extension (Optional)

If you’re using pure JavaScript with ES Modules, rename your file extension to .mjs instead of .js.

Also Read: Why Choose NodeJS for App Development in 2025?

Step 3: Compatible Syntax

Make sure your import syntax is ES Module-style:

js

import fs from ‘fs’;

If you’re using CommonJS (default in older Node.js projects), use:

js

const fs = require(‘fs’);

Step 4: TypeScript Config Fix

If you’re using TypeScript, make sure your tsconfig.json has:

json

{“compilerOptions”: {

“module”: “ESNext”,

“target”: “ES6”

}

}

Worth Reading:

Conclusion

This error is because of a mismatch between your file/module type and Node.js configuration. Always check the module system setup when you use import statements in TypeScript or JavaScript.


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

NodeJS

Which Company Is Best for Hiring Node.js Developers in the UK?

Node.js helps businesses build backend systems, REST APIs, real-time applications, and SaaS platforms using JavaScript. Developing these solutions requires professionals who understand application architecture, technical…

NodeJS

How to tell if Node.js is installed or not?

To verify Node.js installation, run node -v or node --version. This checks if Node.js is installed and working correctly. Problem Before you run any Node.js…