node.js - Squalise:TypeError:没有'new'(打字稿)就不能调用类构造函数模态
问题描述
我在节点中使用打字稿,通过使用以下命令运行我的 index.ts 和 ts-node,它在开发模式下运行良好。
ts-node src/index.ts
但是当我将我的打字稿代码转换为 es6 并使用简单的节点命令运行 index.js 文件时
node dist/index.js
它抛出错误
/home/ubuntu/Projects/projects/Servers/test-server/node_modules/sequelize/lib/sequelize.js:486
this.importCache[importPath] = defineCall(this, DataTypes);
^
TypeError: Class constructor Modal cannot be invoked without 'new'
at Sequelize.import (/home/ubuntu/Projects/projects/Servers/test-server/node_modules/sequelize/lib/sequelize.js:486:38)
下面是我的 tsconfig.json 文件
{
"compilerOptions": {
"target": "ES2015",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
}
}
我尝试了与此错误相关的所有可用解决方案,但对我没有任何作用并且仍然出现此错误。
这是我的续集索引文件。
import { Sequelize } from "sequelize";
import config from "../config";
import fs from "fs";
import path from "path"
export default class Modal {
public db: any = {};
private config = new config().config
constructor() {
this.registerSchemaInDB();
}
private sql: any = new Sequelize(
'mysql://' + this.config.database.username + ':' + this.config.database.password + '@localhost:3306/' + this.config.database.name, {
dialect: "mysql",
host: this.config.database.host
});
private registerSchemaInDB = () => {
fs.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf(".") !== 0) && (file !== "index.ts") ;
})
.forEach((file) => {
console.log(file);
let model = this.sql.import(path.join(__dirname, file));
this.db[model.name] = model;
});
Object.keys(this.db).forEach((modelName) => {
if ("associate" in this.db[modelName]) {
this.db[modelName].associate(this.db);
}
});
this.db.sequelize = this.sql
}
}
节点版本 v12.14.0
续集版本 5.21.3
提前谢谢
解决方案
当我尝试使用构建我的项目时,我也遇到了同样的错误
tsc -p。
构建命令它工作得很好。但在运行构建项目时抛出相同的错误
但我知道我的错误。你只需要重构你的fs.readdirSync条件。
只需用下面的代码替换它
fs.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf(".") !== 0) && (file !== "index.ts") && (file !== "index.js");
})
.forEach((file) => {
console.log(file);
let model = this.sql.import(path.join(__dirname, file));
this.db[model.name] = model;
});
你做错的是你只过滤index.ts文件你还必须检查index,js
推荐阅读
- sql - SQL Server 消耗大部分 CPU 时间
- dns - DNS 无效记录
- javascript - 用 eval() 解析的数组字符串(不是 JSON) - 如何保护?
- sharepoint - AddEventListener 到 SharePoint 模态窗口,以便父窗口可以执行一个函数,在模态窗口中声明
- php - PHP usort 遇到一些问题
- python - 字典理解从循环中产生不同的结果
- python - 如何从头开始在 cbmpy 中创建基因组规模的代谢模型?
- linux - IRQ 中断未被触发
- java - 使用 java 读取 spark 2.2 中的 XML 和键值格式的预期输出
- javascript - 从特定日期开始在 later.js 上每 3 个月和 6 个月重复一次