【发布时间】: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