DEV Community

Cover image for How to Fix “Cannot Use Import Statement Outside a Module” in JavaScript
Meghna Meghwani for ServerAvatar

Posted on

How to Fix “Cannot Use Import Statement Outside a Module” in JavaScript

You run a JavaScript file that looks perfectly valid, yet the process stops before the first useful line executes: Cannot Use Import Statement Outside a Module.

SyntaxError: Cannot use import statement outside a module
Enter fullscreen mode Exit fullscreen mode

The wording makes the import statement look guilty. Usually, it isn’t. The real problem is that your runtime and your source file disagree about the file’s module format.

This guide shows you how to identify that disagreement before changing project settings. You’ll learn how to fix the error in Node.js, a browser, TypeScript, and common development tools without creating a second module problem elsewhere. It is written for developers who want a reliable diagnosis, not a list of unrelated commands to try.

TL;DR

  • First identify which program is executing the file: Node.js, a browser, a test runner, or a TypeScript tool.
  • In Node.js, choose one module system for the relevant package: ESM with "type": "module" or .mjs, or CommonJS with require() and .cjs.
  • In a browser, load an entry file with <script type="module"> and use valid browser-resolvable import paths.
  • In TypeScript, align package.json, tsconfig.json, the emitted JavaScript, and the command that launches it.
  • Don't add Babel or another build tool until you know the current runtime cannot execute the format you intend to use.

What the Error Is Actually Telling You

In Node.js projects, developers commonly encounter two module systems: ECMAScript modules (ESM) and CommonJS (CJS).

If you're getting started with Node.js or deciding whether it fits your application, see our guide to the key reasons Node.js is a strong choice for web development in 2026.

table

Static import declarations belong to ESM. If the runtime parses the same file as a classic script or a CommonJS module, it rejects the syntax before your application starts.

module_format

That detail matters because this is a parsing and configuration error, not normally a package-installation error. Reinstalling node_modules may change nothing. The useful question is:

Why did this specific runtime classify this specific file as something other than an ES module?

Node.js uses explicit markers such as file extensions and the nearest parent package.json to determine a file's format. A browser uses the script element and the module graph. Test runners and transpilers may apply another transformation layer before either one sees the code.

difference_parser

For the complete rules Node.js uses to determine whether a file is treated as ESM or CommonJS, see the Node.js documentation on packages and module formats.

Read the full article: https://serveravatar.com/fix-cannot-use-import-statement-outside-module

Top comments (0)