The main cause of "SyntaxError: Cannot use import statement outside a module" error is non-CommonJS modules (compilerOptions.module
in tsconfig.json), but I got same error with "module": "CommonJS"
.
Initially, my tsconfig.json was:
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"experimentalDecorators": true,
"baseUrl": "./01-Source",
"paths": {
"@EnterpriseBusinessRules/*": [ "./BusinessRules/Enterprise/*"],
// Other aliases
}
}
}
but with this config, ts-node will not understand the aliases and it will be error
Error: Cannot find module '@EnterpriseBusinessRules/XXX/NNN'
Alhgough the ts-node does not understrand the alieses, it understands the import
.
To solve the aliaases issue, I added
{
"compilerOptions": { /* */ },
"ts-node": {
"require": [
"tsconfig-paths/register"
]
}
}
part to *tsconfig.json and now error is
import {
^^^^^^
SyntaxError: Cannot use import statement outside a module
I know that inside ts-node
group we can overwrite the compilerOptions
like:
{
"ts-node": {
"compilerOptions": {
"module": "CommonJS",
"esModuleInterop": true
},
"require": [
"tsconfig-paths/register"
]
}
}
but the module is already CommonJS and esModuleInterop is already true, so I must not to overwrite it (but even is to try, nothing change)
In this case, the cause was not installed ts-node. I executed my .ts file by nodemon which delgates the executing of ts-node when target file is .ts, but ts-node must be installed.