库和角度的“不是构造函数”错误

Chr*_*erg 7 typescript angular

我正在尝试为国际象棋游戏构建 Angular 应用程序。我想将 chess.js https://github.com/jhlywa/chess.js/blob/master/README.md库与https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master中声明的类型一起使用/types/chess.js 但每当我运行应用程序时,运行时就会出现错误。

我已经通过 npm 安装了软件包

npm install --save chess.js @types/chess.js
Run Code Online (Sandbox Code Playgroud)

在使用该库的服务中,我有以下相关代码:

import {Chess, ChessInstance} from "chess.js"

@Injectable({
  providedIn: 'root'
})
export class GameService {

 private chess: ChessInstance = new Chess()

 constructor() {}
 ...
}

Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

core.js:15724 ERROR Error: Uncaught (in promise): TypeError: chess_js__WEBPACK_IMPORTED_MODULE_4__.Chess is not a constructor
TypeError: chess_js__WEBPACK_IMPORTED_MODULE_4__.Chess is not a constructor
Run Code Online (Sandbox Code Playgroud)

我也尝试将其导入为:

import * as Chessjs from "chess.js"

@Injectable({
  providedIn: 'root'
})
export class GameService {

 private chess: Chessjs.ChessInstance = new Chessjs.Chess()

 constructor() {}
 ...
}

Run Code Online (Sandbox Code Playgroud)

没有成功。

我还尝试从我的 app.module.ts 声明 chess.js,但这似乎是导入非模块脚本的错误方法

任何帮助将受到广泛赞赏

JSm*_*ith 8

我无法让它与打字一起工作,因为它Chess没有定义为 a class,而是定义为 aconst

所以首先卸载类型:

npm uninstall --save @types/chess.js
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它。

import * as Chess from "chess.js

chess:any = new Chess();

唯一的问题是你没有类型(经过测试和工作)

更新

基于此答案进行修改,以便您的编辑器识别类型,您可以使用安装的类型进行操作

import { ChessInstance } from 'chess.js'

ChessReq:any = require('chess.js');
Chess:ChessInstance = new this.ChessReq();
Run Code Online (Sandbox Code Playgroud)

然后使用Chess.header()例如编辑器中显示的类型

(经过测试并且也可以工作)


Luc*_*Luc 6

其他答案在所有环境(浏览器、Jest、VSCode)中都不适合我。

这就是我修复它的方法:

import * as ChessJS from "chess.js";

const Chess = typeof ChessJS === "function" ? ChessJS : ChessJS.Chess;

const chess = new Chess();
Run Code Online (Sandbox Code Playgroud)