How to fix 'SyntaxError: Cannot use import statement outside a module'?

How to fix 'SyntaxError: Cannot use import statement outside a module'?

几天前我遇到了这个错误。有几个类似的问题,但没有答案解决我的问题。

发生在我​​运行npm run start,运行宁npm run build

之后

为什么 npm run start 运行 扩展名为 .ts 的文件像 ormconfig.ts?这是正确的行为吗?不应该 ormconfig.js 运行 吗?

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

从“./src/entities/Booking”导入{预订}

语法错误:无法在模块外使用导入语句 在 Object.compileFunction(节点:vm:352:18) 在 wrapSafe(节点:internal/modules/cjs/loader:1031:15) 在 Module._compile(节点:internal/modules/cjs/loader:1065:27) 在 Object.Module._extensions..js(节点:internal/modules/cjs/loader:1153:10) 在 Module.load(节点:internal/modules/cjs/loader:981:32) 在 Function.Module._load(节点:internal/modules/cjs/loader:822:12) 在 Module.require(节点:internal/modules/cjs/loader:1005:19) 在要求(节点:internal/modules/cjs/helpers:102:18) 在 ConnectionOptionsReader。 (C:\Users\franc\Code\f5\server\node_modules\typeorm\connection\ConnectionOptionsReader.js:120:46) 在步骤 (C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:143:27) 在 Object.next(C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:124:57) 在 C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:117:75 在新的承诺 () 在 __awaiter(C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:113:16) 在 ConnectionOptionsReader.load(C:\Users\franc\Code\f5\server\node_modules\typeorm\connection\ConnectionOptionsReader.js:92:38) 在 ConnectionOptionsReader。 (C:\Users\franc\Code\f5\server\node_modules\typeorm\connection\ConnectionOptionsReader.js:34:55)

PS: 这是我在平台上的第一个问题,如果有缺失的数据告诉我!对不起我的英语:)

ormconfig.ts 移动到您的 src 文件夹(必要时更改导入),并在 compilerOptions 之后添加 include 以包含 src 中的所有内容.使用 exclude node_modules 和测试也是一个好主意:

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

可能是因为 TypeScript 在编译输出中包含 ormconfig.ts:正如您在构建文件夹中看到的那样,有一个 index.js 和 ormconfig.js 并且重复 src文件夹。