Chessjs cannot be imported without using es6 syntax

Viewed 49

In all of the chessjs documentation, const chess = require('chess'); is used.

However, when I try to use this syntax, I get this error:

const Chess = require('chess');
              ^

Error [ERR_REQUIRE_ESM]: require() of ES Module is not supported.
Instead change the require of main.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> {
  code: 'ERR_REQUIRE_ESM'
}

Is there a solution for this?

2 Answers

The dynamic import() looks like this

async function loader(){
  const Chess = await import('chess')
  // things with Chess
}

As Evert mentioned, this can also cover the conditional import in an ESModule

Although this isn't the solution to the general question (which is why I'm not marking this as the solution), I ended up just migrating away from the module chess which doesn't allow commonjs requires to the module chess.js which allows both.

New code:

const { Chess }= require('chess.js');
Related