Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Not a constructor" error with library and angular

Im trying to build an Angular application for a chessgame. I want to use the library chess.js https://github.com/jhlywa/chess.js/blob/master/README.md with the types declared in https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/chess.js But whenever i run the application theres an error on runtime.

I've installed the packages through npm with

npm install --save chess.js @types/chess.js

And in the service that uses the library i've got this relevant code:

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

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

 private chess: ChessInstance = new Chess()

 constructor() {}
 ...
}

The error i get is:

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

I've also tried importing it as:

import * as Chessjs from "chess.js"

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

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

 constructor() {}
 ...
}

To no success.

I've also tried declaring chess.js from my app.module.ts, but that seems to be the wrong way about importing non-module scripts

Any help would be widely appreciated

like image 962
Christoffer Nørbjerg Avatar asked Dec 17 '22 15:12

Christoffer Nørbjerg


1 Answers

I can't get it to work with the typings because Chess is not defined as a class but as a const

so first uninstall types:

npm uninstall --save @types/chess.js

and then use it like this.

import * as Chess from "chess.js

chess:any = new Chess();

the only issue is that you won't have the types (tested and working)

UPDATE

based on this answer with modifications, so your editor recognizes the types, you could do with the types installed

import { ChessInstance } from 'chess.js'

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

then use Chess.header() for example with the types appearing on your editor

(tested and working too)

like image 80
JSmith Avatar answered Dec 30 '22 11:12

JSmith