javascript - 从 Typescript 转译时 NodeJS 存在导入问题

标签 javascript node.js typescript typeorm

我已经使用nodejs实现了简单的rest api,并通过typeorm连接到数据库。以下是我编写的一些代码片段:

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  Unique,
  CreateDateColumn,
  UpdateDateColumn
} from "typeorm";
import { Length, IsNotEmpty } from "class-validator";
import bcrypt from "bcryptjs";

@Entity()
@Unique(["username"])
export class User {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column()
  @Length(4, 20)
  username: string;
}

tsconfig.json

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "es6",
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "emitDecoratorMetadata": true
    },
    "lib": [
        "es2015"
    ]
}

package.json

{
    "name": "node-with-ts",
    "version": "1.0.0",
    "description": "",
    "main": "dist/app.js",
    "scripts": {
        "start": "tsc && node dist/app.js",
        "test": "echo \"Error: no test specified\" && exit 1",
        "tsc": "tsc",
        "prod": "node ./dist/app.js",
        "build": "npm install && tsc -p .",
        "reset": "rm -rf node_modules/ && rm -rf dist/ && npm run build",
        "migration:run": "ts-node ./node_modules/typeorm/cli.js migration:run"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "@types/express": "^4.16.1",
        "@types/node": "^12.7.5",
        "nodemon": "^1.19.2",
        "ts-node": "8.4.1",
        "tslint": "^5.12.1",
        "typescript": "^3.3.3"
    },
    "dependencies": {
        "@types/bcryptjs": "^2.4.2",
        "@types/body-parser": "^1.17.0",
        "@types/cors": "^2.8.4",
        "@types/helmet": "0.0.42",
        "@types/jsonwebtoken": "^8.3.0",
        "bcryptjs": "^2.4.3",
        "body-parser": "^1.18.1",
        "class-validator": "^0.9.1",
        "cors": "^2.8.5",
        "express": "4.17.1",
        "helmet": "^3.21.1",
        "jsonwebtoken": "^8.4.0",
        "reflect-metadata": "^0.1.13",
        "sqlite3": "^4.1.0",
        "ts-node-dev": "^1.0.0-pre.32",
        "typeorm": "^0.2.12"
    }
}

我粘贴了很多代码,因为我不知道出了什么问题。我尝试通过 npm run start 运行应用程序,它会抛出以下错误:

> tsc && node dist/app.js

    /Users/workspace/node_typescript_project/src/entity/User.ts:1
    (function (exports, require, module, __filename, __dirname) { import {
                                                                  ^^^^^^

    SyntaxError: Unexpected token import

虽然我能够构建项目并生成 js 代码,但是当运行应用程序时它会抛出错误。

最佳答案

您的实体可能没有在 Typeorm 配置文件中正确引用。

尝试看看是否可以使用以下 ormconfig.js 文件(特别注意 entities 属性:

// ormconfig.js at root of project
const isDevelopment = process.env.NODE_ENV === 'development';
module.exports = {
  type: 'mysql',
  host: process.env.MYSQL_HOST,
  port: process.env.MYSQL_TCP_PORT,
  username: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
  synchronize: isDevelopment,
  logging: isDevelopment,
  entities: [
    isDevelopment ? `src/**/*.entity.ts` : `dist/**/*.entity.js`,
  ],
  migrations: [`src/migration/**/*.ts`],
  subscribers: ['src/subscriber/**/*.ts'],
  cli: {
    entitiesDir: 'src/entity',
    migrationsDir: 'src/migration',
    subscribersDir: 'src/subscriber',
  },
};

通过此设置,我可以让 ts-node 直接使用我的 Typescript 源文件,并且只有在生产中我才使用 tsc 进行构建。在构建产品时,我需要引用 dist 文件夹内的 .js 文件。

关于javascript - 从 Typescript 转译时 NodeJS 存在导入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148222/

相关文章:

javascript - 如果失败,则使用if/else Javascript语句禁用过渡动画

javascript - 在 Model.belongsTo 调用不是 Sequelize.Model 实例的东西

javascript - 如何将 LitElement 组件和 Elix 组件一起扩展?

javascript - 使用 Typescript 延迟加载模式

c# - 如何修复重建 TypeScript 错误 @types/node

javascript - 如何使用 Controller (ASP.NET M V C) 的结果填充部分 View

javascript - 使用同一按钮在窗口重新加载后调用函数

javascript - 如何访问 firefox 浏览器的 object.style.filter?

javascript - Facebook Messenger,发送回执时暂时发送消息失败

node.js - gitignore 所有node_modules 目录和子目录