【问题标题】:Unable to execute Typescript, NodeJS, and Sequelize due to a Model Error由于模型错误,无法执行 Typescript、NodeJS 和 Sequelize
【发布时间】:2021-06-14 09:00:22
【问题描述】:

我正在尝试在 NodeJS 上运行 sequelize。我正在用 Typescript 编写代码 我使用的软件版本如下:

nodejs - 14.16.0 续集 - 6.5.1 typescript - 4.2.3

Typescript 可以正确构建,但是在针对已编译的 index.js 文件运行 node 命令时,出现以下错误:

import { DataTypes, Model, Sequelize, TableHints } from 'sequelize';
                    ^^^^^
SyntaxError: Named export 'Model' not found. The requested module 'sequelize' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'sequelize';
const { DataTypes, Model, Sequelize, TableHints } = pkg;

代码是一个简单的index.ts

import { DataTypes, Model, Optional, Sequelize, TableHints } from 'sequelize';

let server = "server";
let database = "db";
let user_name = "user";
let password = "password";

let app_name = "api";

let _mssql_service = new Sequelize(database, user_name, password, {
  dialect: "mssql",
  isolationLevel: TableHints.READUNCOMMITTED,
  host: server,
  dialectOptions: {
    options: {
      appName: app_name,
    },
  },
});

// These are all the attributes in the User model
export interface TrackingAttributes {
  id: number;
  column1: string;
   ...
}

interface TrackingCreationAttributes
  extends Optional<TrackingAttributes, "id"> {}

export class TrackingModel
  extends Model<TrackingAttributes, TrackingCreationAttributes>
  implements TrackingAttributes {
  public id!: number; // Note that the `null assertion` `!` is required in strict mode.
  public column1!: string;
  ...
}

async function test() {
  try {
   TrackingModel.init(
      {
        id: {
          type: DataTypes.INTEGER.UNSIGNED,
          autoIncrement: true,
          primaryKey: true,
        },
        column1: {
          type: DataTypes.STRING(10),
          allowNull: true
        },
      },
      {
        tableName: "table1",
        schema: "schema1",
        sequelize: _mssql_service, // passing the `sequelize` instance is required
      }
    );
    let val = await TrackingModel.findOne({ where: { id: 24 } });
    console.log("Connection has been established successfully.");
    console.log(val);
  } catch (error) {
    console.error("Unable to connect to the database:", error);
  } finally {
    _mssql_service.close();
  }
}
test();

我在 package.json 中安装并包含以下类型:

"@types/node": "^14.14.35", "@types/sequelize": "^4.28.9", "@types/validator": "^13.1.3"

我有以下 tsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "module": "esnext",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "strict": true,
    "declaration": true,
    "outDir": "bin",
    "types": ["node"],
    "typeRoots": ["../node_modules/@types"],
    "sourceMap": true
  },
  "include": ["**/*.ts"],
  "exclude": ["tests", "dist", "node_modules", "lib", "bin"]
}

我有以下 package.json

{
  "name": "console-application",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "sequelize": "^6.5.1"
  },
  "devDependencies": {
    "@types/node": "^14.14.35",
    "@types/validator": "^13.1.3"
  }
}

我很困惑为什么会收到此错误,但我们将不胜感激。

【问题讨论】:

    标签: node.js typescript sequelize.js


    【解决方案1】:

    通常@types/* 包与它们提供类型的包的主要版本相匹配。在这种情况下,您有 sequelize v6 但 @types/sequelize v4 所以它们不匹配。

    我查看了 sequelize 存储库,发现它们从 v5 开始就提供了自己的类型,因此您应该卸载 @types/sequelize,因为它们是不需要的,并且是导致问题的原因。

    查看我找到的信息 - https://sequelize.org/master/manual/typescript.html

    编辑:在 OP 更新他们的帖子以包含它之后,tsconfig.json/package.json 问题中的附加信息。

    首先,您需要在依赖项列表中包含typescript。您可以简单地运行npm i typescript(或根据需要使用特定版本)。

    那么,您的tsconfig.json 的问题是您已将module 编译器选项设置为esnext,但Node 不支持此功能(Node 确实 具有实验性支持为此通过--experimental-modules 标志,但我现在忽略它)。您应该将其设置为 commonjs

    工作tsconfig.json:

    {
      "compilerOptions": {
        "target": "es2020",
        "module": "commonjs",
        "esModuleInterop": true,
        "moduleResolution": "node",
        "strict": true,
        "declaration": true,
        "outDir": "bin",
        "types": ["node"],
        "typeRoots": ["../node_modules/@types"],
        "sourceMap": true
      },
      "include": ["**/*.ts"],
      "exclude": ["tests", "dist", "node_modules", "lib", "bin"]
    }
    

    有了这个我能够编译和运行代码,虽然我现在得到一个单独的错误,即来自 sequelize 的 Error: Please install tedious package manually - 但这只是一个依赖问题。

    【讨论】:

    • 谢谢。我试过了,但没有用。我针对该类型运行了 npm uninstall 命令,然后使用 tsc 重新编译,然后运行 ​​node 命令,但出现了我报告的相同错误。我还尝试删除 node_modules 文件夹,然后删除 tsc..node 命令。结果相同
    • 我自己用你发布的确切代码和一个基本的 tsconfig.json 进行了尝试,它对我来说很好用。您能否发布您的 tsconfig.json 以及您的 package.json 吗?
    • 我添加了您要求的信息。感谢您的帮助
    • 您可以尝试从您的tsconfig.json 中删除typeRoots 属性吗?我认为这可能是问题所在。如果没有,我会在有机会时使用您的确切文件进行测试
    • @thxmike 我已经用一些额外的帮助更新了我的答案,应该可以解决您的问题
    猜你喜欢
    • 1970-01-01
    • 2019-01-23
    • 2019-09-27
    • 1970-01-01
    • 2019-08-05
    • 2021-07-20
    • 2013-05-21
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多