node module_error ai_generated true

SyntaxError: Cannot use import statement outside a module

ID: node/cannot-use-import

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
20 active

Root Cause

ES module import used in CommonJS context. Need type:module in package.json or .mjs extension.

generic

Workarounds

  1. 95% success Add "type": "module" to package.json
    { "type": "module" }

    Sources: https://nodejs.org/api/packages.html#type

  2. 90% success Rename file to .mjs extension
    mv index.js index.mjs
    node index.mjs

    Sources: https://nodejs.org/api/esm.html#enabling

  3. 85% success Use dynamic import(): const mod = await import('module')
    const mod = await import('module')

    Sources: https://nodejs.org/api/esm.html#import-expressions

Dead Ends

Common approaches that don't work:

  1. Change all imports to require() 60% fail

    May break if the dependency only exports ESM

  2. Add babel transpilation 65% fail

    Overkill — Node natively supports ESM

Error Chain

Frequently confused with: