"Not a constructor" error with library and angular

Viewed 3533

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

4 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)

None of the other answers worked for me in all environments (browser, Jest, VSCode).

This is how I fixed it:

import * as ChessJS from "chess.js";

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

const chess = new Chess();

You can import it like this

import * as Chess from 'chess.js';

and use it like:

const chess: Chess = new Chess();

I'm using chess.js version 0.10.3 and I found that @yazantahhan was partially correct. The following works for me. Just make sure the path to your file is correct as it may differ from mine.

import * as Chess from './chess';
const chess = new Chess();
Related