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.