简体   繁体   中英

Failed execution of untyped typescript module

I'm trying to integrate Typescript in a project build with webpack. I have a library that does not come with ts definition ( chess.js ), so I used an external definition library ( @types/chess.js ).

I managed to get the code to compile without any errors, but when it is executed in the browser I got the following error:

TypeError: i.Chess is not a constructor

Here is the typescript code that does not work:

import {Chess} from 'chess.js';

const board = new Chess();

The chess.js module does not have typescript types associated. Here is how this module is exported.

var Chess = function(fen) {
    // ...
}

/* export Chess object if using node or any other CommonJS compatible
 * environment */
if (typeof exports !== 'undefined') exports.Chess = Chess;
/* export Chess object for any RequireJS compatible environment */
if (typeof define !== 'undefined') define( function () { return Chess;  });

Here is the ts types I use declares the chess.js module.

/**
 * The chess.js function that is used to build chess game instances.
 * It can be used with or without `new` to build your instance. Both variants
 * work the same.
 */
export const Chess: {
    (fen?: string): ChessInstance;

    new (fen?: string): ChessInstance;
};

And here is my tsconfig.json:

Here is my tsconfig file:

{
  "compilerOptions": {
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "allowJs": true
  }
}

The webpack configuration I use is the same as defined in the webpack basic TS setup guide .

declare module also

declare module 'chess.js' {
  type ChessInstance = any
  export const Chess: {
    (fen?: string): ChessInstance;

    new (fen?: string): ChessInstance;
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM