angular - "Not a constructor"库和 Angular 错误

标签 angular typescript

我正在尝试为国际象棋游戏构建一个 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

在使用该库的服务中,我有以下相关代码:
import {Chess, ChessInstance} from "chess.js"

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

 private chess: ChessInstance = new Chess()

 constructor() {}
 ...
}


我得到的错误是:
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

我也尝试将其导入为:
import * as Chessjs from "chess.js"

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

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

 constructor() {}
 ...
}


没有成功。

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

任何帮助将不胜感激

最佳答案

我无法让它与打字一起工作,因为 Chess未定义为 class但作为 const
所以首先卸载类型:

npm uninstall --save @types/chess.js

然后像这样使用它。
import * as Chess from "chess.jschess:any = new Chess();
唯一的问题是你不会有类型(测试和工作)

更新

基于此answer进行修改,因此您的编辑器可以识别类型,您可以使用已安装的类型
import { ChessInstance } from 'chess.js'

ChessReq:any = require('chess.js');
Chess:ChessInstance = new this.ChessReq();

然后使用 Chess.header()例如编辑器上出现的类型

(也经过测试和工作)

关于angular - "Not a constructor"库和 Angular 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58598457/

相关文章:

json - 利用浏览器缓存 - Firebase/Angular 5

Angular 的 CSS .cdk-virtual-scroll-content-wrapper 未应用

Angular 6 http.delete 请求不起作用

typescript - 如何在单独的文件中声明和导入 typescript 接口(interface)

angular - 属性 'format' 在类型 'Duration' 上不存在

javascript - 有没有办法以 Angular 形式将 json 键作为字符串 @Input() 传递

Angular HTTP 拦截器执行内部 http 请求两次

angular - 我可以自定义 Angular 全局错误处理程序,使其不仅仅是一个错误参数吗?

testing - 在生产模式下隐藏 angular2 组件的最佳解决方案?

typescript - 包括串联的 Typescript JS outFile - Angular 2 + Typescript