Knex:不能在模块外使用导入语句

时间:2021-02-01 14:43:47

标签: javascript module knex.js

我想在我的 next.js/express/postgres-project 中使用 knex。

根据 next/vercel 示例 (https://github.com/vercel/next.js/tree/canary/examples/with-knex) 我有:

  • knexfile.js (root) 和我的配置
  • knex/index.js 使用以下代码:

import knex from "knex";
    import config from "../knexfile.js";
    let cached = global.pg;
    if (!cached) cached = global.pg = {};
    
    export function getKnex() {
      if (!cached.instance) cached.instance = knex(config);
      return cached.instance;
    }

在我的 API 端点中,我使用以下代码:

import { getKnex } from "../../knex"; 

const Signup = async (req, res) => {
  const knex = getKnex(); 
  try {
   //logic
}

现在我收到错误: "import { getKnex } from "../../knex"; SyntaxError: 不能在模块外使用 import 语句。

我尝试在 package.json 中添加 {"type": "module"}。但后来我开始收到新的错误,比如 "const express = require("express"); ReferenceError: require is not defined"。 这以前有效,所以我想这是因为package.json 中的更改。

我的问题:错误来自哪里,有没有办法解决它(除了在 package.json 中添加 {"type": "module"}

0 个答案:

没有答案