我找到了一个网站https://github.com/typeorm/typeorm,只需几个步骤,它创建了一个能够连接到PostgreSQL数据库的打字稿应用程序。我按照步骤操作,并修改了示例以连接到我自己的现有数据库,并成功获取一个表的内容。不过,我的目标是创建一个部署到nodeJS的REST服务,该服务能够提供对存储在PostgreSQL数据库中的持久数据的访问。我找到了另一个网站,其中包含一个我想做的事(超过2个部分)的示例以及更多内容。 https://itnext.io/production-ready-node-js-rest-apis-setup-using-typescript-postgresql-and-redis-a9525871407第2部分将介绍PostgreSQL的集成。第2部分似乎从未发布过,因此我得到了一个看起来不错的开始的节点应用程序。因此,我自己尝试集成缺少的部分,以便部署到节点REST服务的代码可以访问我的数据库。当使用此脚本启动代码时,代码按预期工作时:
"start": "ts-node src/index.ts"
此脚本在import语句上的实体源中导致输入typeorm所需类的错误:
"dev": "tsc-watch --onSuccess \"node ./build/src/index.js\""
这里是错误:
/Users/jboss/projects/typescript/backend/src/entity/Banners.ts:1
import { Column, Entity, BaseEntity } from "typeorm";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:983:16)
at Module._compile (internal/modules/cjs/loader.js:1033:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1103:10)
at Module.load (internal/modules/cjs/loader.js:914:32)
at Function.Module._load (internal/modules/cjs/loader.js:822:14)
at Module.require (internal/modules/cjs/loader.js:956:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Function.PlatformTools.load (/Users/jboss/projects/typescript/backend/node_modules/typeorm/platform/PlatformTools.js:114:28)
at /Users/jboss/projects/typescript/backend/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69
at Array.map (<anonymous>)
这是ormconfig内容:
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "jboss",
"password": "bluegrass",
"database": "video",
"synchronize": false,
"logging": true,
"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": "backend",
"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": {
"pg": "^7.18.2",
"reflect-metadata": "^0.1.13",
"typeorm": "^0.2.24"
},
"scripts": {
"dev": "tsc-watch --onSuccess \"node ./build/src/index.js\"",
"start": "ts-node src/index.ts",
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js"
}
}
这是tsconfig.json内容:
{
"compilerOptions": {
"lib": [
"es5",
"es6"
],
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./build",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true
}
}
我希望有人能给我一些提示,使我可以做这项工作。
您要检查ormconfig.json中的“ entities”属性。
应该是类似的东西
{
//...
"entities": ["build/src/entity/*.*"]
}