【问题标题】:typeORM combine next.js can not connect database with errortypeORM combine next.js 无法连接数据库报错
【发布时间】:2020-12-11 11:55:42
【问题描述】:

我尝试将 TypeORM 与 next.js 框架一起使用。

我的连接是:

const create =  () => {
    // @ts-ignore
    return createConnection({
        ...config
    });
};
export const getDatabaseConnection = async () => {
    console.log("======getDatabaseConnection====");
    const manager = getConnectionManager();
    const current = manager.has('default') ? manager.get('default'): (await create());
    console.log(current.isConnected)
    await current.connect().catch(e=> console.log(e))
    console.log("======success====");
    console.log(current.isConnected)
    if(current.isConnected){
        console.log("current connected")
    }else{
        await current.connect()
        console.log("current  reconnect")
    }
    return current;
};

控制台是:

======getDatabaseConnection====
false
/mnt/c/workgit/orm/src/entity/Contact.ts:1
import {Entity, Column, ManyToOne, PrimaryGeneratedColumn} from "typeorm";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1167:16)
    at Module._compile (internal/modules/cjs/loader.js:1215:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
    at Module.load (internal/modules/cjs/loader.js:1100:32)
    at Function.Module._load (internal/modules/cjs/loader.js:962:14)
    at Module.require (internal/modules/cjs/loader.js:1140:19)
    at require (internal/modules/cjs/helpers.js:75:18)
    at Function.PlatformTools.load (/mnt/c/workgit/orm/node_modules/typeorm/platform/PlatformTools.js:114:28)
    at /mnt/c/workgit/orm/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69
    at Array.map (<anonymous>)
======success====
false

为什么每次我尝试连接数据库,然后连接仍然没有连接。 我的 tsconfig.json 是:

{
   "compilerOptions": {
     "emitDecoratorMetadata": true,
     "experimentalDecorators": true,
     "noImplicitAny": true,
     "baseUrl": ".",
     "target": "es5",
     "module": "commonjs",
     "strict": false,
     "esModuleInterop": true,
     "lib": [
       "dom",
       "dom.iterable",
       "esnext"
     ],
     "allowJs": true,
     "skipLibCheck": true,
     "forceConsistentCasingInFileNames": true,
     "noEmit": true,
     "moduleResolution": "node",
     "resolveJsonModule": true,
     "isolatedModules": true,
     "jsx": "preserve"
   },
   "exclude": [
     "node_modules"
   ],
   "include": [
     "next-env.d.ts",
     "**/*.ts",
     "**/*.tsx"
   ]
 }

不能简单地在 package.json 文件中应用 type:"module",因为错误:

 [ERR_REQUIRE_ESM]: Must use import to load ES Module: /mnt/c/workgit/orm/.next/server/pages/api/user/signup.js
require() of ES modules is not supported.
require() of /mnt/c/workgit/orm/.next/server/pages/api/user/signup.js from /mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename signup.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /mnt/c/workgit/orm/package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1268:13)
    at Module.load (internal/modules/cjs/loader.js:1100:32)
    at Function.Module._load (internal/modules/cjs/loader.js:962:14)
    at Module.require (internal/modules/cjs/loader.js:1140:19)
    at require (internal/modules/cjs/helpers.js:75:18)
    at DevServer.handleApiRequest (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js:48:175)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async Object.fn (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js:40:218)
    at async Router.execute (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/router.js:38:67)
    at async DevServer.run (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js:49:494) {
  code: 'ERR_REQUIRE_ESM'

【问题讨论】:

标签: typescript connection next.js typeorm


【解决方案1】:

如果您的 ormconfig 迁移/实体属性指向 .ts 文件,则可能会出现问题。解决此问题的一种方法是在将这些属性传递给 createConnection 函数时覆盖这些属性,如下所示:

createConnection({
  ...config,
  entities: [Contact],
  migrations: []
});

在 Github 上引用此评论:https://github.com/typeorm/typeorm/issues/6241#issuecomment-643690383

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 2019-11-01
    • 2021-10-19
    • 2021-07-29
    • 2021-05-26
    • 2019-07-10
    • 2023-03-25
    • 2012-12-06
    相关资源
    最近更新 更多