Home > front end >  How to fix 'SyntaxError: Cannot use import statement outside a module'?
How to fix 'SyntaxError: Cannot use import statement outside a module'?

Time:02-19

I have this error a couple of days ago. There are several similar questions but no answer solved my problem.

It happens when I run npm run start, after running npm run build

Why does npm run start run files with a .ts extension like ormconfig.ts? Is it correct behavior? Shouldn't ormconfig.js run?

  • Full error message

C:\Users\franc\Code\f5\server\ormconfig.ts:1

import { Booking } from "./src/entities/Booking"

SyntaxError: Cannot use import statement outside a module at Object.compileFunction (node:vm:352:18) at wrapSafe (node:internal/modules/cjs/loader:1031:15) at Module._compile (node:internal/modules/cjs/loader:1065:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at ConnectionOptionsReader. (C:\Users\franc\Code\f5\server\node_modules\typeorm\connection\ConnectionOptionsReader.js:120:46) at step (C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:143:27) at Object.next (C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:124:57) at C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:117:75 at new Promise () at __awaiter (C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:113:16) at ConnectionOptionsReader.load (C:\Users\franc\Code\f5\server\node_modules\typeorm\connection\ConnectionOptionsReader.js:92:38) at ConnectionOptionsReader. (C:\Users\franc\Code\f5\server\node_modules\typeorm\connection\ConnectionOptionsReader.js:34:55)

  • package.json

enter image description here

  • tsconfig.json

enter image description here

  • Project strcture

enter image description here

PS: this is my first question on the platform, if there is missing data tell me! and sorry for my english :)

CodePudding user response:

Move ormconfig.ts to your src folder (change imports if necessary), and add the include after compilerOptions to include everything in the src. It's also a good idea to use exclude node_modules and tests:

{
    "compilerOptions": { ... },
    "include": ["src/**/*.ts"],
    "exclude": ["node_modules", "tests"]
}

It might be because TypeScript is including ormconfig.ts in the compilation output: as you can see in the build folder there is an index.js and ormconfig.js AND duplicate src folder.

  • Related