【问题标题】:Syntax Error on TypeScript file when using TypeORM with JavaScript file将 TypeORM 与 JavaScript 文件一起使用时,TypeScript 文件出现语法错误
【发布时间】: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 时,我需要重新包含该目录。

我的问题是:

  1. 当我运行 .js 文件时,为什么 Node [通过 TypeORM] 给我一个关于 .ts 文件的错误?
  2. 是否可以进行一些配置设置以使两个目录都到位而不出现错误?

【问题讨论】:

    标签: javascript node.js typescript typeorm


    【解决方案1】:

    @ObiHill

    您必须在 package.json 中将 type 设置为模块,例如:

    "type": "module"
    

    【讨论】:

      猜你喜欢
      • 2017-09-05
      • 2013-04-05
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      相关资源
      最近更新 更多