Fix "SyntaxError: Cannot use import statement outside a module"
SyntaxError: Cannot use import statement outside a module
- Uncaught SyntaxError: Cannot use import statement outside a module
- Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/chalk/source/index.js from /app/index.js not supported.
- ReferenceError: require is not defined in ES module scope, you can use import instead
- (node:1234) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
- SyntaxError: import declarations may only appear at top level of a module
A file uses the ES modules import syntax while it is loaded as a classic script or as CommonJS. In Node.js, add "type": "module" to package.json or rename the file to .mjs; in the browser, use <script type="module">; with Jest or TypeScript, configure the transform.
What this error means
JavaScript has two module systems: CommonJS (require, module.exports), historically used by Node.js, and ES modules (import, export), the language standard. The import keyword is only allowed in a file loaded as a module. Node.js treats a .js file as CommonJS if the nearest package.json contains "type": "commonjs" (or has no type on older versions), a .cjs file always as CommonJS and a .mjs file always as an ES module. The browser requires type="module" on the <script> tag. The opposite error, ERR_REQUIRE_ESM, happens when CommonJS calls require() on an ESM-only package on a Node.js version older than 20.19 or 22.12.
Common causes
- Node.js project in CommonJS:
package.jsondeclares"type": "commonjs"(recent versions ofnpm initadd it) or has notypeon an older Node.js version, but the code usesimport. - Browser script without
type="module":<script src="app.js">loads the file as a classic script. - Jest: Jest runs tests as CommonJS; without a Babel transform or ESM mode, it fails on
import, including inside an ESM-only package innode_modules. - TypeScript / ts-node: the
tsconfig.json"module"setting does not match thepackage.jsontype, or a compiled file keepsimportstatements in a CommonJS project. - ESM-only package loaded with
require(ERR_REQUIRE_ESM):chalk5,node-fetch3 ornanoid4 and later on an old Node.js.
Step-by-step fix
-
Identify the context
Look at what runs the file: the browser ("Uncaught SyntaxError" in the console), Node.js (
node index.js), Jest ("Jest encountered an unexpected token") or a TypeScript tool. Also check the Node.js version withnode -v. -
Browser: declare the script as a module
Add
type="module". The page must be served over HTTP (for example with Vite ornpx serve): opened withfile://, the module is blocked.<script type="module" src="/js/app.js"></script> -
Node.js: switch the project to ES modules
Add
"type": "module"topackage.json. Relative imports must then include the extension (./utils.js), andrequireand__dirnameno longer exist: useimportandimport.meta.dirname(Node.js 20.11+). For a single file, rename it to.mjsinstead.{ "name": "my-app", "type": "module", "scripts": { "start": "node src/index.js" } } -
Or stay in CommonJS
If the project must stay CommonJS, replace
importwithrequire. For an ESM-only package (ERR_REQUIRE_ESM), upgrade Node.js to 22.12+ (or 20.19+), whererequire()of an ES module works, or use a dynamicimport().const express = require('express'); // ESM-only package from CommonJS async function main() { const { default: chalk } = await import('chalk'); console.log(chalk.green('ok')); } main(); -
Jest: transform the code or switch to Vitest
With Babel, Jest transforms your files automatically. Packages in
node_modulesare not transformed by default: add ESM packages to thetransformIgnorePatternsexception. Alternative: Vitest, which handles ES modules natively with a Jest-like API.// npm install --save-dev @babel/preset-env // babel.config.cjs module.exports = { presets: [['@babel/preset-env', { targets: { node: 'current' } }]], }; // jest.config.cjs module.exports = { transformIgnorePatterns: ['/node_modules/(?!(nanoid|lodash-es)/)'], }; -
TypeScript: align
tsconfig.jsonand usetsxWith
"module": "nodenext", TypeScript follows thepackage.jsontypeand emits the right format. To run a.tsfile directly,tsxhandles ESM and CommonJS with no configuration, whereasts-nodeneeds specific options for ESM.npm install --save-dev tsx npx tsx src/index.ts
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Pick a single module system per project and declare it explicitly with
"type"inpackage.json; keep.cjsand.mjsfor exceptions. - Use a recent Node.js LTS version, which detects ESM syntax and allows
require()of synchronous ES modules. - Before adding a dependency, check whether it is ESM-only (
"type": "module"orexportsfield in itspackage.json).
Frequently asked questions
What is the difference between .mjs and .cjs?
.mjs forces the file to be an ES module (import/export) and .cjs forces it to be CommonJS (require/module.exports), whatever the package.json type says.
How do I get __dirname in an ES module?
Use import.meta.dirname and import.meta.filename (Node.js 20.11+). On older versions: path.dirname(fileURLToPath(import.meta.url)).
Why "require is not defined in ES module scope" after adding "type": "module"?
Every .js file in the project is now an ES module, where require does not exist. Replace require with import, or rename the files that must stay CommonJS to .cjs.
Useful tools for this error
More JavaScript & Node.js errors
- Fix "Cannot read properties of undefined" in JavaScript
- Fix "blocked by CORS policy: No 'Access-Control-Allow-Origin' header"
- Fix "Unexpected token '<', "<!DOCTYPE "... is not valid JSON"
- Fix "Error: Cannot find module" in Node.js
- Fix "npm ERR! ERESOLVE unable to resolve dependency tree"
- Fix "Hydration failed because the server rendered HTML didn’t match the client" (React, Next.js)
- Fix "Too many re-renders. React limits the number of renders" in React
- Fix "Error: listen EADDRINUSE: address already in use" in Node.js