node.js - 意外的 token 导入nodejs, typescript

标签 node.js typescript typeorm

当我尝试启动我的应用程序时,我正在我的项目中使用 typescript、gruntjs、typeorm、typeorm-model-generator 来开发 Web API 我收到一个 unexpected token import 错误,但那是因为当它必须读取我所有 js 文件所在的 dist 目录时,正在读取我的 typescript 文件的位置,并且只有在以下情况下才会发生此错误我添加了与我的数据库建立连接所需的代码。

app.ts

export class Server {

 public app: express.Application; 

 public static bootstrap(): Server {
     return new Server();
 }

 constructor() {
    this.app = express();

    this.config();
    this.api();
 }

  private config(): void {
    this.app.use(express.static(path.join(__dirname, "public")));

    this.app.use(logger('dev'));
    this.app.use(bodyParser.json());
    this.app.use(bodyParser.urlencoded({
        extended: true
    }));

    this.app.use(function (error: any,
        request: express.Request, response: express.Response,
        next: express.NextFunction) {
            console.log(error);
            error.status = 404;
            response.json(error);
        });
  }

  private api(): void {
   // code that causes error
   // the output I recieve says
   // ./src/entity/myEntity.ts:1 unexpected token import
   // but if I remove it everything works fine
   typeorm.createConnection().then(async connection => {
        console.log("Conexion establecida");
    }).catch(error => {
        console.log(error)
    });
  }

}

这是我的tsconfig.json

{
    "compilerOptions": {
        "lib": [
            "es5",
            "es6"
        ],
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "rootDir": "src",
        "outDir": "./dist/",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "sourceMap": false,
        "noImplicitAny": false
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

我做错了什么?我应该自杀吗?

最佳答案

我最近遇到了这个问题。问题可能出在您的 ormconfig.json 中。生成的 ormconfig.json 指向 src 文件夹中的实体作为要调用的实体,而不是 dist 或 build 文件夹中的实体 js 文件。检查我也问的问题:SyntaxError: Unexpected token import typeORM entity

关于node.js - 意外的 token 导入nodejs, typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753097/

相关文章:

node.js - NodeJs如何写入文件

html - 错误错误 : ExpressionChangedAfterItHasBeenCheckedError in Angular 5

javascript - 如何在 Typescript 中生成 * 数组

typescript - VS代码/w。在 TypeScript Monorepo 中更漂亮

postgresql - 使用 TypeORM 保存实体列表

node.js - NestJS : Case-insensitive search in PostgreSQL

node.js - 如何使用 mongoose 聚合查询在内部数组中使用 $group

mysql - Node.js Sequelize 虚拟列从其他模型中提取值(value)

与数据库的 typescript 连接

python - 尝试使用 python AWS CDK 创建空堆栈时返回 JSII 错误