【问题标题】:NodeJS problems with imports when transpiling from typescript从打字稿转译时,NodeJS 的导入问题
【发布时间】:2019-10-01 09:45:15
【问题描述】:

我已经用nodejs 实现了简单的rest api,并通过typeorm 连接到数据库。这是我写的一些sn-ps代码:

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 代码,但在运行应用程序时会引发错误。

【问题讨论】:

  • 你能给我们你的节点版本吗?在终端node -v。您的问题是 import 是 ES6 关键字,而您的节点版本似乎无法处理此问题。
  • 节点:v8.9.4 npm:6.11.3
  • 你能展示你的项目文件夹结构吗?

标签: javascript node.js typescript typeorm


【解决方案1】:

您的实体可能没有在您的 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 来构建。在为 prod 构建时,我需要引用 dist 文件夹中的 .js 文件。

【讨论】:

    【解决方案2】:

    我正在尝试复制该问题,但无法复制它。刚刚为上述代码创建了一个示例 repo。

    https://github.com/pktippa/stackoverflow-questions/tree/master/58148222

    【讨论】:

    • 为什么你的包锁json里有Babel?
    • 你有哪个node和npm?
    • babel 被安装是因为 tslint 需要它,并且 tslint 是 package.json 中的一个 devDependency。操作系统:Windows 10 Pro NodeJs:8.15.0 NPM:6.7.0
    【解决方案3】:

    尝试不同的导入语法,例如: 从“bcryptjs”导入 { bcrypt };

    其他导入语法示例见here

    【讨论】:

      【解决方案4】:

      Node.js 不处理 ES6 语法、导入等。 为此,您必须将 ES6 代码转换为 ES5,您可以使用 Babel => https://github.com/babel/example-node-server

      如果你不想使用 Babel,你可以简单地将 import 替换为 require

      const bcrypt = require("bcryptjs");  // same as 'import * as bcrypt from "bcryptjs";'
      

      【讨论】:

      • Node 只处理 es6 与 mjs 文件一起使用,并开启了实验标志。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2022-08-18
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多