node
config_error
ai_generated
true
SyntaxError: Cannot use import statement outside a module (ts-node)
ID: node/ts-node-syntax-error
90%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 20 | active | — | — | — |
Root Cause
ts-node can't handle ESM syntax. Needs tsconfig configuration for ESM.
genericWorkarounds
-
92% success Use ts-node with --esm flag: ts-node --esm script.ts
ts-node --esm script.ts
Sources: https://typestrong.org/ts-node/docs/imports#native-ecmascript-modules
-
88% success Set 'module': 'nodenext' and 'moduleResolution': 'nodenext' in tsconfig.json
'nodenext' and 'moduleResolution': 'nodenext' in tsconfig.json
-
90% success Consider tsx as a drop-in replacement: npx tsx script.ts (faster, less config)
npx tsx script.ts (faster, less config)
Sources: https://www.npmjs.com/package/tsx
Dead Ends
Common approaches that don't work:
-
Convert all imports to require()
70% fail
Defeats the purpose of TypeScript ES modules
Error Chain
Frequently confused with: