首页 > 解决方案 > nodejs应用程序在依赖项中的打字稿文件上抛出意外的令牌

问题描述

我有一个 nodejs 应用程序,我在其中为存储库层引入了 TypeORM。
我已经为 node_modules 依赖项中的意外令牌错误苦苦挣扎了好几天。

为了追查根本原因,我创建了一个非常简单的应用程序,基于 TypeORM 文档中描述的示例应用程序。我添加了 dotenv 作为依赖项和一个非常简单的环境文件,当我尝试使用 TypeORM 连接到数据库时,我确实在 .../dotenv/types/test.ts 中遇到了错误。我不知道为什么应用程序试图解析该文件。

我尝试使用 ts-node 运行应用程序以及使用 tsc 编译代码并直接运行应用程序。结果相同。我还在 tsconfig.json 中尝试了几个目标,并尝试使用 esm 运行项目。到目前为止没有运气。

我一定做错了什么,我希望这里有人能指出那是什么。我在github 存储库中添加了引发错误的基本应用程序

这是错误:

/Users/quintmouthaan/projects/weareeves/eves-api/node_modules/dotenv/types/test.ts:1
(function (exports, require, module, __filename, __dirname) { import { config, parse } from "dotenv";
                                                                     ^
SyntaxError: Unexpected token {
    at new Script (vm.js:83:7)
    at createScript (vm.js:267:10)
    at Object.runInThisContext (vm.js:319:10)
    at Module._compile (internal/modules/cjs/loader.js:685:28)
    at Module._extensions..js (internal/modules/cjs/loader.js:733:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/quintmouthaan/projects/prj/api/node_modules/ts-node/src/index.ts:384:14)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Module.require (internal/modules/cjs/loader.js:658:17)

这是我的 tsconfig.json 文件:

{
   "compilerOptions": {
      "lib": [
         "es5",
         "es6"
      ],
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./build",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true,
      "allowJs": true
   }
}

和 ormconfig.json 文件:

{
   "type": "postgres",
   "host": "localhost",
   "port": 5432,
   "username": "postgres",
   "password": "",
   "database": "db",
   "synchronize": true,
   "logging": false,
   "entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],
   "cli": {
      "entitiesDir": "src/entity",
      "migrationsDir": "src/migration",
      "subscribersDir": "src/subscriber"
   }
}

最后是 package.json 文件:

{
   "name": "TestTypeORM",
   "version": "0.0.1",
   "description": "Awesome project developed with TypeORM.",
   "devDependencies": {
      "ts-node": "3.3.0",
      "@types/node": "^8.0.29",
      "typescript": "3.3.3333"
   },
   "dependencies": {
      "dotenv": "^8.2.0",
      "pg": "^7.3.0",
      "reflect-metadata": "^0.1.10",
      "typeorm": "0.2.20"
   },
   "scripts": {
      "start": "ts-node src/index.ts"
   }
}

标签: node.jstypescripttypeormunexpected-token

解决方案


好的,我想通了。这确实是一个愚蠢的错误。

我设置了环境变量 TYPEORM_ENTITIES=**/*.ts 因为这个 TypeORM 在所有 foders 中寻找实体,包括 node_modules 并且在连接时导致错误。

我在这方面花了太多时间,所以我希望这至少可以帮助其他人:-)。


推荐阅读