【发布时间】:2022-07-01 07:27:48
【问题描述】:
运行 TypeScript 编译的 JS 文件 [通过 TypeORM] 时出现 SyntaxError。
我有以下文件:
// ./src/entity/Bird.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Bird {
@PrimaryGeneratedColumn()
id: number;
@Column()
kingdom: string;
@Column({length: 300})
phylum: string;
@Column()
class: String;
@Column({type: 'simple-array'})
colors: string[];
@Column({default: false})
isActive: boolean;
@Column({type: 'bigint', width: 100, default: Date.now()})
timestamp_u: number;
}
// ./init.ts
import 'reflect-metadata';
import { createConnection } from 'typeorm';
async function start() {
// initialize database
let connection = await createConnection();
// close connection
await connection.close();
}
start().catch(console.error);
// ./ormconfig.json
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "my~password",
"database": "sandbox",
"synchronize": true,
"logging": false,
"entities": [
"dist/src/entity/**/*.js",
"src/entity/**/*.ts"
]
}
// ./tsconfig.json
{
"compilerOptions": {
"lib": [
"es5",
"es6"
],
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./dist",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true
},
"exclude": ["node_modules", "dist", "out"]
}
在package.json 中,type 设置为commonjs [使ts-node 正常工作];
我正在将 TypeScript 编译为 JavaScript:
npx tsc
然后我通过 Node 运行 JavaScript:
node ./dist/init.js
当我这样做时,我收到以下错误:
Bird.ts:1
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
^^^^^^
SyntaxError: Cannot use import statement outside a module
当我将ormconfig.json 更改为此问题时,问题就消失了:
...
"entities": [
"dist/src/entity/**/*.js"
]
...
注意:我已经删除了 TypeScript 文件的实体目录。
但是,当我使用 ts-node 时,我需要重新包含该目录。
我的问题是:
- 当我运行
.js文件时,为什么 Node [通过 TypeORM] 给我一个关于.ts文件的错误? - 是否可以进行一些配置设置以使两个目录都到位而不出现错误?
【问题讨论】:
标签: javascript node.js typescript typeorm