ProjectStack
npm

SyntaxError: Cannot use import statement outside a module

You're using ES module import syntax (import x from 'y') in a file that Node.js is treating as CommonJS. Node.js needs to know the file is an ES module before it will allow import statements.

Common causes

  • The file uses import/export but package.json doesn't have "type": "module"
  • The file extension is .js but the project is configured as CommonJS
  • Mixing require() and import in the same file
  • A dependency you're using switched to ESM-only and your project is still CommonJS

How to fix it

  1. Add "type": "module" to your package.json to make all .js files use ESM
  2. Or rename the file to .mjs to use ESM for just that file
  3. Or convert import statements to require(): const x = require('y')
  4. If the error is in a dependency, see the ERR_REQUIRE_ESM section for that fix

Example

SyntaxError: Cannot use import statement outside a module at wrapSafe (node:internal/modules/cjs/loader:1383:16) at Module._compile (node:internal/modules/cjs/loader:1425:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1435:10)

Running node index.js where index.js uses import statements without "type": "module" in package.json

Have a different error?

Paste any error message into the Error Translator to get an instant explanation.