首页 > 解决方案 > 使用节点运行编译的 JavaScript 代码时出错

问题描述

我正在尝试将我的打字稿代码编译成 commonjs 以将其与 node.js 一起使用。但是在运行 node 后我收到了这个错误dist/server/src/index.js

Server listening at http://localhost:3002
Error: Cannot use import statement outside a module
    at /home/maxime/Dev/JeuxDuPlacard/packages/server/dist/server/src/index.js:10:55
    at /home/maxime/Dev/JeuxDuPlacard/packages/server/dist/server/src/technical/typeorm/connexion.js:60:21
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

我不明白为什么会出现这个错误,因为我import在编译的 js 文件中没有看到任何语句。

例如这里是dist/server/index.js

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
var connexion_1 = require("./technical/typeorm/connexion");
var app_1 = __importDefault(require("./app"));
var port = 3002;
connexion_1.createConnection(function (error) { throw new Error(error.message); })
    .catch(function (error) { return console.log(error); });
app_1.default.listen(port, function () { return console.log("Server listening at http://localhost:" + port); });
//# sourceMappingURL=index.js.map

我不想{ "type"="module" }在我的 package.json 文件中使用顶级字段,因为我import只想在我的开发环境中使用该语法(使用 typescript)并保留常规的 commonjs 模块分辨率以使用 node.js 运行我的应用程序。

我正在使用节点14.15.4

我做错了什么?

我的package.json文件

   "name": "server",
   "version": "1.0.0",
   "main": "index.js",
   "license": "MIT",
   "private": true,
   "type": "commonjs",
   "scripts": {
      "test": "echo testing server",
      "start": "tsc --watch",
      "build": "tsc"
   },
   "dependencies": {
      "@types/cors": "^2.8.9",
      "@types/jsonwebtoken": "^8.5.0",
      "bcrypt": "^5.0.0",
      "body-parser": "^1.19.0",
      "cors": "^2.8.5",
      "express": "^4.17.1",
      "jsonwebtoken": "^8.5.1",
      "pg": "^8.4.0",
      "reflect-metadata": "^0.1.10",
      "typeorm": "0.2.29",
      "validate.js": "^0.13.1"
   },
   "devDependencies": {
      "@types/bcrypt": "^3.0.0",
      "@types/express": "^4.17.9",
      "@types/node": "^14.14.8",
      "ts-node": "3.3.0",
      "ts-node-dev": "^1.0.0",
      "typescript": "^4.0.5"
   },
   "engines": {
      "node": "^14"
   }
}

和我的tsconfig.json

    "compilerOptions": {
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "es5",
        "moduleResolution": "node",
        "sourceMap": true,
        "baseUrl": "./",
        "outDir": "dist",
        "strict": true,
        "lib": ["es2017"],
        "noImplicitAny": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "incremental": false,
        "paths": {
            "*": ["node_modules/*"],
            "business/*": ["src/business"],
            "technical/*": ["src/technical"]
        }
    },
    "include": [
        "./**/*",
        "../common/**/*"
    ]
} 

ormconfig.ts

import { ConnectionOptions } from 'typeorm';
import path from 'path';

const HOST : string = process.env.DB_HOST || "localhost";
const PORT : number =  Number(process.env.DB_PORT) || 5432;
const USER_NAME : string = process.env.DB_USERNAME || "test";
const PASSWORD : string = process.env.DB_PASSWORD || "test";
const DATABASE : string = process.env.DB_NAME || "test";

const fileBaseName : string = path.basename(__filename);
const fileExtention : string = path.extname(fileBaseName);

const ORMConfig = {
   type: "postgres",
   host: HOST,
   port: PORT,
   username: USER_NAME,
   password: PASSWORD,
   database: DATABASE,
   synchronize: true,
   logging: false,
   entities: [
      `src/business/**/*.entity${fileExtention}`
   ],
   migrations: [
      `src/migration/**/*${fileExtention}`
   ]
} as ConnectionOptions;

module.exports = ORMConfig;

我的项目结构

.
├── dist // contains my compiled js files
├── docker
│   ├── database.env
│   └── docker-compose.yaml
├── ormconfig.ts // where my connection options are living
├── package.json
├── README.md
├── src
|   ...
│   ├── index.ts
│   └── technical
|       ...
│       ├── typeorm
│       │   ├── connexion.ts
│       │   └── repository
│       │       └── createGetRepository.ts
│       ...
├── tsconfig.json
├── yarn-error.log
└── yarn.lock

谢谢,

马克西姆

标签: javascriptnode.jstypescriptnode-modules

解决方案


经过一番研究,我终于弄清楚出了什么问题:

我试图在node dist/src/index.js不怀疑 ormconfig 文件的正确位置的情况下启动我编译的 js 代码(是 dist/ 文件夹中的那个,还是我的项目根目录中的另一个?)

为了在我的文件中检索我的连接选项,我dist/src/technical/typeorm/connexion.js认为 typeorm 会在我的dist文件夹根目录中的 ormConfig.js 文件中进行搜索。

然后我从 typeOrm github 存储库中的ConnectionOptionReader类中阅读了以下注释行:

    constructor(protected options?: {
        /**
         * Directory where ormconfig should be read from.
         * By default its your application root (where your app package.json is located).
         */
        root?: string,

此时,typeOrm 会尝试从错误的 ormconfig.ts 文件中读取连接选项(位于我的项目根目录的那个,也是我的所有代码都使用 import 语句的开发环境),这就是错误的来源.

愿这个解释对将来会犯同样错误的人有所帮助。


推荐阅读