Need Help With Node Development?

Work with our skilled Node developers to accelerate your project and boost its performance.

Hire Node.js Developers

Support On Demand!

Understanding the Error

When using TypeScript or JavaScript with ES Modules (import/export syntax), you might encounter the following error:
SyntaxError: Cannot use import statement outside a module

This happens when Node.js or the TypeScript compiler does not recognize your file as an ES Module.

Solutions to Fix the Error

1. Ensure type: “module” is in package.json

For Node.js to recognize ES Module syntax, update your package.json file:

{
  "type": "module"
}

If your project uses CommonJS (require() syntax), remove “type”: “module” or use dynamic imports instead.

2. Use .mts or .mjs File Extensions

TypeScript recognizes .mts files as ES Modules. If you’re using JavaScript, rename .js to .mjs.

Example:

myfile.ts → myfile.mts

3. Configure tsconfig.json for ES Modules

Ensure your TypeScript configuration supports ES Modules by updating tsconfig.json:

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

Then, recompile your TypeScript files:
tsc

4. Use import() Instead of import Statements

If you’re dynamically importing a module, use import():

(async () => {
  const module = await import('./myModule.js');
  console.log(module.default);
})();

5. Run the Script with –loader in Node.js

If you’re running your script with Node.js, use:

node --loader ts-node/esm myfile.ts

or for JavaScript:

node --experimental-modules myfile.mjs

Final Notes

  • Always check if your project setup matches the module system you’re using.
  • Use CommonJS (require()) if you don’t need ES Modules.
  • For modern projects, stick with ES Modules and configure your environment accordingly.

By following these steps, you can resolve the “Cannot use import statement outside a module” error in TypeScript.

Related Q&A