当我 运行 我用节点编译的 JavaScript 代码时出错
Error when i'm running my compiled JavaScript code with node
我正在尝试将我的打字稿代码编译成 commonjs 以将其与节点一起使用。但是我在 运行 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)
我不明白为什么会出现这个错误,因为我在编译的 js 文件中没有看到任何 import
语句。
例如这里是 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
我不想在我的 package.json 文件中使用顶级字段 { "type"="module" }
,因为我只想在我的开发环境中使用 import
语法(与打字稿) 并保持 运行 我的应用程序与节点的常规 commonjs 模块解析。
我正在使用节点 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
谢谢,
马克西姆
经过一些研究,我终于弄清楚出了什么问题:
我试图用 node dist/src/index.js
启动我编译的 js 代码,但我怀疑 ormconfig 文件的正确位置(是 dist/ 文件夹中的那个,还是我项目根目录中的另一个)那会涉及到吗?)
为了在我的 dist/src/technical/typeorm/connexion.js
文件中检索我的连接选项,我认为 typeorm 会在我的 dist 文件夹的根目录中的 ormConfig.js 文件中搜索.
然后我从 typeOrm github 存储库中阅读了 ConnectionOptionReader class 中的注释行:
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 文件(位于我项目的 root 以及我的开发环境中的文件中读取连接选项我所有的代码都在使用 import 语句),这就是错误的来源。
希望这个解释能对以后犯同样错误的人有所帮助。
我正在尝试将我的打字稿代码编译成 commonjs 以将其与节点一起使用。但是我在 运行 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)
我不明白为什么会出现这个错误,因为我在编译的 js 文件中没有看到任何 import
语句。
例如这里是 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
我不想在我的 package.json 文件中使用顶级字段 { "type"="module" }
,因为我只想在我的开发环境中使用 import
语法(与打字稿) 并保持 运行 我的应用程序与节点的常规 commonjs 模块解析。
我正在使用节点 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
谢谢,
马克西姆
经过一些研究,我终于弄清楚出了什么问题:
我试图用 node dist/src/index.js
启动我编译的 js 代码,但我怀疑 ormconfig 文件的正确位置(是 dist/ 文件夹中的那个,还是我项目根目录中的另一个)那会涉及到吗?)
为了在我的 dist/src/technical/typeorm/connexion.js
文件中检索我的连接选项,我认为 typeorm 会在我的 dist 文件夹的根目录中的 ormConfig.js 文件中搜索.
然后我从 typeOrm github 存储库中阅读了 ConnectionOptionReader class 中的注释行:
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 文件(位于我项目的 root 以及我的开发环境中的文件中读取连接选项我所有的代码都在使用 import 语句),这就是错误的来源。
希望这个解释能对以后犯同样错误的人有所帮助。