Programming & Coding How-TosTechnology

“Cannot Use Import Statement Outside a Module” in Node? Fix

Admin
"Cannot Use Import Statement Outside a Module" in Node? Fix

You install a package, copy a modern code example, and run your file with Node.js. Instead of your program, you get a hard stop: SyntaxError: Cannot use import statement outside a module. The code looks correct. The example came from official docs. So why does Node refuse to run it?

This error is about how Node decides which module system a file uses. Node supports two systems, and your file is being read with the wrong one. In this guide you will learn why the error happens and the three clean ways to fix it, so you can pick the right one for your project.

Quick Answer

The “Cannot use import statement outside a module” error happens because Node.js treats your file as CommonJS by default, and import syntax only works in ES modules. Fix it by adding "type": "module" to your package.json, renaming the file to end with .mjs, or converting the import lines to CommonJS require() calls. Choose one approach for the whole project and use it consistently.

Why Node Has Two Module Systems

Node created its own module system called CommonJS before JavaScript had a standard one. Files load others with require() and share code with module.exports.

Later, JavaScript gained an official system called ECMAScript modules, or ESM, using import and export. Node supports both systems and must decide, file by file, which rules to apply.

That decision is the heart of your error. Node looked at your file, decided it was CommonJS, and then met an import statement, which is illegal under CommonJS rules. The fix is to tell Node the truth about your file. The exact decision rules are laid out in the Node.js documentation on ECMAScript modules and how file types are determined.

How Node Decides the Type of a File

  • Files ending in .mjs are always treated as ES modules.
  • Files ending in .cjs are always treated as CommonJS.
  • Files ending in .js follow the nearest package.json. If it contains "type": "module", they are ESM. Otherwise, they are CommonJS.

Once you see this list, the error stops being mysterious. Your .js file almost certainly sits under a package.json with no type field, or with "type": "commonjs", so Node reads it as CommonJS.

Fix 1: Add “type”: “module” to package.json

This is the best fix for a new project that will use import everywhere. It tells Node that every .js file in the project is an ES module.

Follow these steps:

  1. Open the package.json file in the root of your project. If none exists, create one by running npm init -y in the project folder.
  2. Add a top-level field so the file includes "type": "module" alongside fields like "name" and "version".
  3. Save the file and run your script again with node yourfile.js.

After this change, your import statements will work. But be careful: the change affects the whole project. Every .js file must now use ESM rules. Any file still using require() or module.exports will break with a new error, such as require is not defined in ES module scope. Convert those files too, or give the few CommonJS files a .cjs extension so they keep the old behavior.

Important ESM Rules After the Switch

ES modules in Node are stricter than many tutorials show. Keep these rules in mind:

  • Relative imports need the full file extension: write import helper from './helper.js', not './helper'.
  • The variables __dirname and __filename do not exist in ESM. Use import.meta.url with the url and path modules to rebuild them when you truly need them.
  • JSON files cannot be imported with a plain import in older Node versions without an import attribute. Reading the file with the fs module is often simpler.

Fix 2: Rename the File to .mjs

If you only have one file, or you want ESM in just part of a project, rename the file so its name ends with .mjs instead of .js. For example, rename app.js to app.mjs and run it with node app.mjs.

The extension alone tells Node to use ES module rules for that file. This is perfect for small scripts inside a CommonJS project, and a fast way to test whether the module type is really your problem.

For a growing application, pick Fix 1 or Fix 3 as the project standard instead, for consistency.

Fix 3: Convert import Statements to require()

If your project is an existing CommonJS project, the least disruptive fix is to stop using import in that file and use require() instead. This keeps the project’s current system and changes only your code.

The conversions follow simple patterns:

  1. import fs from 'fs'; becomes const fs = require('fs');
  2. import { readFile } from 'fs'; becomes const { readFile } = require('fs');
  3. import express from 'express'; becomes const express = require('express');
  4. Your own exports change too: export default becomes module.exports =, and named exports become properties on exports.

One limitation matters. A few modern packages are ESM-only and publish no CommonJS build. A require() of such a package may fail with an ERR_REQUIRE_ESM error. Very recent Node versions have relaxed this for some packages, but you cannot rely on it everywhere. If the package you need is ESM-only, switch the project with Fix 1 or isolate that part of the code in an .mjs file.

While working through Node version issues like this, you might also hit runtime differences in built-in tools. Our companion guide on fixing the fetch is not defined error in Node.js explains another common case where code from the browser or a tutorial assumes features your Node setup does not provide by default.

Do Not Mix Systems Carelessly

Most follow-up errors come from mixing systems without a plan. An ES module can import a CommonJS package, which is why importing older libraries usually works after you switch to ESM.

The reverse direction is the fragile one. CommonJS files trying to load ESM files have historically failed, and dynamic import() workarounds add complexity. Rather than learning every edge case, follow one rule: decide the project’s main system, write new files in that system, and mark exceptions clearly with .cjs or .mjs extensions. This rule prevents the whole family of module errors, not just today’s one.

What About TypeScript and Frameworks?

If you use TypeScript or a framework, check the module setting in your config first, since it controls how imports are compiled. Always test with the project’s real start script.

Common Mistakes and Useful Tips

  • Editing the wrong package.json: in nested projects, Node uses the nearest package.json above the file. Make sure you edit that one, not a parent or child project’s file.
  • Adding the field in the wrong place: "type" must be a top-level field, not inside "scripts" or "dependencies". JSON syntax errors here can create strange new failures.
  • Forgetting file extensions in ESM imports: after switching, relative imports fail without the .js extension. This is the most common second error people meet.
  • Half-converting a project: changing package.json but leaving require() calls in other files just trades one error for another. Search the project for both require( and module.exports before you switch.
  • Running the file with an old Node version: very old Node releases have partial ESM support. Run node --version and use a current LTS release for predictable behavior.
  • Copying browser code directly: examples written for the browser assume ESM and browser globals. Node needs the module type set correctly and may lack some browser APIs.

A reliable debugging tip: create a tiny test file with a single import line and run it. If the tiny file works after your change but your real file still fails, the remaining problem is inside your real file’s other code, not the module setting. Small tests keep the search honest.

Conclusion

The “Cannot use import statement outside a module” error simply means Node read your file as CommonJS while your code uses ESM syntax. Fix it by setting "type": "module" in package.json for ESM projects, using the .mjs extension for single files, or converting to require() for CommonJS projects. Pick one system, apply it consistently, and remember the ESM details like full file extensions. With that, the error disappears and stays gone.

Frequently Asked Questions

Why does import work in my tutorial’s project but not in mine?

The tutorial’s project almost certainly has "type": "module" in its package.json, or its files use the .mjs extension. Your project is being treated as CommonJS by default. Compare the two package.json files and the difference will be visible at once.

Is ESM better than CommonJS for new Node projects?

For most new projects, yes. ESM is the official JavaScript standard, works in browsers and Node with the same syntax, and is the direction the ecosystem is moving. Existing CommonJS projects can keep working for years, so there is no need to rewrite a stable project only for fashion.

What does ERR_REQUIRE_ESM mean?

It means CommonJS code tried to require() a package that only ships as an ES module. The clean fix is to load that package from ESM code, either by switching the project to "type": "module" or by using a dynamic import() call in the specific place that needs it.

Why do I get “require is not defined” after adding type module?

Because the change converts all .js files to ES modules, where require does not exist. Convert those files to import syntax, or rename the files that must stay CommonJS to use the .cjs extension so Node keeps the old rules for them.

Do I need to add file extensions to imports in Node ESM?

Yes, for your own relative files. Node ESM does not guess extensions or folder index files the way many bundlers do. Write the complete path, such as ./utils/helper.js, even in TypeScript projects where the source file ends in .ts but the imported path refers to the compiled output.

Admin

Passionate about the intersection of style and storytelling. I simplify fashion trends and industry news into easy-to-follow advice, helping you stay stylish and informed in the fast-paced world of fashion.

Leave a Reply

Your email address will not be published. Required fields are marked *