Skip to content
FR
  1. LuzineDebug
  2. JavaScript & Node.js
  3. SyntaxError: Cannot use import statement outside…
JavaScript & Node.js Intermediate ≈ 15 min to fix

Fix "SyntaxError: Cannot use import statement outside a module"

Error message
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
In short

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.

Be the first to confirm this fix

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

  1. Node.js project in CommonJS: package.json declares "type": "commonjs" (recent versions of npm init add it) or has no type on an older Node.js version, but the code uses import.
  2. Browser script without type="module": <script src="app.js"> loads the file as a classic script.
  3. Jest: Jest runs tests as CommonJS; without a Babel transform or ESM mode, it fails on import, including inside an ESM-only package in node_modules.
  4. TypeScript / ts-node: the tsconfig.json "module" setting does not match the package.json type, or a compiled file keeps import statements in a CommonJS project.
  5. ESM-only package loaded with require (ERR_REQUIRE_ESM): chalk 5, node-fetch 3 or nanoid 4 and later on an old Node.js.

Step-by-step fix

  1. 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 with node -v.

  2. Browser: declare the script as a module

    Add type="module". The page must be served over HTTP (for example with Vite or npx serve): opened with file://, the module is blocked.

    xml
    <script type="module" src="/js/app.js"></script>
  3. Node.js: switch the project to ES modules

    Add "type": "module" to package.json. Relative imports must then include the extension (./utils.js), and require and __dirname no longer exist: use import and import.meta.dirname (Node.js 20.11+). For a single file, rename it to .mjs instead.

    json
    {
      "name": "my-app",
      "type": "module",
      "scripts": {
        "start": "node src/index.js"
      }
    }
  4. Or stay in CommonJS

    If the project must stay CommonJS, replace import with require. For an ESM-only package (ERR_REQUIRE_ESM), upgrade Node.js to 22.12+ (or 20.19+), where require() of an ES module works, or use a dynamic import().

    javascript
    const express = require('express');
    
    // ESM-only package from CommonJS
    async function main() {
      const { default: chalk } = await import('chalk');
      console.log(chalk.green('ok'));
    }
    main();
  5. Jest: transform the code or switch to Vitest

    With Babel, Jest transforms your files automatically. Packages in node_modules are not transformed by default: add ESM packages to the transformIgnorePatterns exception. Alternative: Vitest, which handles ES modules natively with a Jest-like API.

    javascript
    // 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)/)'],
    };
  6. TypeScript: align tsconfig.json and use tsx

    With "module": "nodenext", TypeScript follows the package.json type and emits the right format. To run a .ts file directly, tsx handles ESM and CommonJS with no configuration, whereas ts-node needs specific options for ESM.

    bash
    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" in package.json; keep .cjs and .mjs for 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" or exports field in its package.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

All JavaScript & Node.js errors →