首页 > 解决方案 > 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

提前谢谢

标签: node.jstypescriptsequelize.js

解决方案


当我尝试使用构建我的项目时,我也遇到了同样的错误

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


推荐阅读