ProfCalculus
ProfCalculus

Reputation: 15

How to wrap IIFE library as vue3 component?

I am attempting to wrap the chessboardjs library inside a Vue3 Typescript component. chessboardjs has a typings file and my editor's IntelliSense shows that it is corrrectly importing the typings. The library exports a function ChessBoard() that looks like a constructor/factory for a ChessBoardInstance; @types/chessboardjs/index.d.ts declares it like this:

export interface ChessBoardFactory {
    (containerElOrId: any, config?: BoardConfig): ChessBoardInstance;
    (containerElOrId: any, position: string | BoardPositionType): ChessBoardInstance;
    fenToObj(fen: string): boolean | BoardPositionType;
    objToFen(obj: BoardPositionType): boolean | string;
}

export const ChessBoard: ChessBoardFactory;

(other declarations omitted).

My component code (script part only) looks like this:

<script lang="ts">
import { ChessBoard, ChessBoardInstance } from "chessboardjs";
import { defineComponent } from "vue";

export default defineComponent({
  name: "ChessBoard",
  data() {
    return new (class {
      board: ChessBoardInstance | null = null;
    })();
  },
  mounted() {
    this.board = ChessBoard("board", "start");
  },
});
</script>

This code compiles, but fails at runtime on the mounted() hook, with the message

Uncaught (in promise) TypeError: Object(...) is not a function

I also tried using this.board = ChessBoard("board", "start"); in the mounted() hook instead of the above, but that fails to compile, with the message:

'new' expression, whose target lacks a construct signature, implicitly has an 'any' type VueDX/TS(7009)

Can someone please help me understand what's going on here, and/or suggest a better approach?

Upvotes: 1

Views: 301

Answers (0)

Related Questions