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.

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" } }

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.
Related

How to Get the Project Root Path in Node.js When working with large Node.js projects, you often need to find the root directory at runtime…

15 Oct, 2025

If you’re trying to run nodemon from the terminal and see the error: nodemon: command not found, it usually means the nodemon package is not…

10 Oct, 2025

Writing to files is a common task in Node.js, whether for logging, saving uploads or creating reports. Node.js has various methods through the built-in fs…

07 Oct, 2025