简体   繁体   English

TypeScript Typeorm 节点模块导入错误:SyntaxError: Unexpected token {

[英]TypeScript Typeorm Node module import error: SyntaxError: Unexpected token {

I'm trying to create a project using TypeScript with Express and Typeorm.我正在尝试使用带有 Express 和 Typeorm 的 TypeScript 创建一个项目。

I keep getting the following error when I'm trying to run the server using node dist/index.js after compilation with tsc .在使用tsc编译后尝试使用node dist/index.js运行服务器时,我不断收到以下错误。

> typescript-express-boilerplate@1.0.0 start /home/yusta/Desktop/project
> npm run serve


> typescript-express-boilerplate@1.0.0 serve /home/yusta/Desktop/project
> node dist/index.js

Example index listening on port 3000!
/home/yusta/Desktop/project/src/entity/User.ts:1
(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)

Interestingly, running ts-node src/index.ts works fine:有趣的是,运行ts-node src/index.ts工作正常:

Example index listening on port 3000!
Saved a new user with id: 2
Loading users from the database...
Loaded users:  [ User { id: 2, email: 'hello@hello.com', password: 'password' } ]

I believe it's a problem with tsconfig.json, but I already set module to commonjs as you can see below.我相信这是 tsconfig.json 的问题,但我已经将module设置为commonjs ,如下所示。

tsconfig.json配置文件

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es2018",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      "*": [
        "node_modules/*",
        "src/types/*"
      ]
    },
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
  },
  "include": [
    "src/**/*"
  ]
}

package.json包.json

{
  "name": "typescript-express-boilerplate",
  "version": "1.0.0",
  "description": "Boilerplate project for TypeScript with ExpressJS.",
  "engines": {
    "node": "10.x"
  },
  "scripts": {
    "start": "npm run serve",
    "serve": "node dist/index.js",
    "build": "npm run tslint && npm run build:ts",
    "build:ts": "tsc",
    "dev": "concurrently -k -p \"[{name}]\" -n \"TypeScript,Node\" -c \"cyan.bold,green.bold\" \"npm run watch:ts\" \"npm run watch:node\"",
    "watch:node": "nodemon dist/index.js",
    "watch:ts": "tsc -w",
    "tslint": "tslint -c tslint.json -p tsconfig.json",
    "heroku-postbuild": "npm install && npm run build"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "express": "^4.16.4",
    "oauth2orize": "^1.11.0",
    "passport": "^0.4.0",
    "passport-http-bearer": "^1.0.1",
    "pg": "^7.8.1",
    "reflect-metadata": "^0.1.13",
    "typeorm": "^0.2.14"
  },
  "devDependencies": {
    "@types/express": "^4.16.1",
    "@types/node": "^11.10.4",
    "@types/oauth2orize": "^1.8.5",
    "@types/passport": "^1.0.0",
    "@types/passport-http-bearer": "^1.0.33",
    "concurrently": "^4.1.0",
    "nodemon": "^1.18.10",
    "tslint": "^5.13.0",
    "typescript": "^3.3.3333"
  }
}

index.ts索引.ts

import "reflect-metadata";
import express from "express";
import { createConnection } from "typeorm";
import { User } from "./entity/User";

createConnection().then(async connection => {
    const user = new User();
    user.email = "hello@hello.com";
    user.password = "password";
    await connection.manager.save(user);
    console.log("Saved a new user with id: " + user.id);

    console.log("Loading users from the database...");
    const users = await connection.manager.find(User);
    console.log("Loaded users: ", users);
}).catch(error => console.log(error));

// Create a new express application instance
const app: express.Application = express();

app.get("/", function (req: express.Request, res: express.Response) {
    res.send("Hello World!");
});

app.listen(process.env.PORT || 3000, function () {
    console.log("Example index listening on port 3000!");
});

entity/User.ts实体/用户.ts

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column({
        length: 30
    })
    email: string;

    @Column()
    password: string;
}

Thanks in advance.提前致谢。

Edit:编辑:

The compiled JavaScript code does not have ES6 import statements, it uses commonjs modules:编译后的 JavaScript 代码没有 ES6 导入语句,它使用了 commonjs 模块:

index.js索引.js

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const express_1 = __importDefault(require("express"));
const typeorm_1 = require("typeorm");
const User_1 = require("./entity/User");
typeorm_1.createConnection().then(async (connection) => {
    const user = new User_1.User();
    user.email = "hello@hello.com";
    user.password = "password";
    await connection.manager.save(user);
    console.log("Saved a new user with id: " + user.id);
    console.log("Loading users from the database...");
    const users = await connection.manager.find(User_1.User);
    console.log("Loaded users: ", users);
}).catch(error => console.log(error));
// Create a new express application instance
const app = express_1.default();
app.get("/", function (req, res) {
    res.send("Hello World!");
});
app.listen(process.env.PORT || 3000, function () {
    console.log("Example index listening on port 3000!");
});
//# sourceMappingURL=index.js.map

entity/User.js实体/用户.js

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = require("typeorm");
let User = class User {
};
__decorate([
    typeorm_1.PrimaryGeneratedColumn(),
    __metadata("design:type", Number)
], User.prototype, "id", void 0);
__decorate([
    typeorm_1.Column({
        length: 30
    }),
    __metadata("design:type", String)
], User.prototype, "email", void 0);
__decorate([
    typeorm_1.Column(),
    __metadata("design:type", String)
], User.prototype, "password", void 0);
User = __decorate([
    typeorm_1.Entity()
], User);
exports.User = User;
//# sourceMappingURL=User.js.map

Create ormconfig.json in the project root (near package.json).在项目根目录(package.json 附近)创建ormconfig.json It should have the following content:它应该有以下内容:

{
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "test",
    "password": "test",
    "database": "test"
}

If you want to run your code in Node.js, you need to tell typescript to transpile the ES module syntax to CommonJS.如果你想在 Node.js 中运行你的代码,你需要告诉 typescript 将 ES 模块语法转换为 CommonJS。 In your tsconfig:在您的 tsconfig 中:

"module": "commonjs",

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM