1

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?

4
  • You may follow the steps defined here for the solution: gist.github.com/sindresorhus/… Commented Sep 20, 2022 at 5:47
  • @kavigun the problem is that I cannot migrate the entire project to ESM. I require some modules depending on an if statement in the middle of my index file, which you can't do with esm because imports have to be top-level only. Commented Sep 20, 2022 at 6:21
  • You can use await import() for those inline cases Commented Sep 20, 2022 at 6:55
  • 2
    That is also the syntax you need if you want to import a ESM module in a CJS file Commented Sep 20, 2022 at 6:57

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I never knew this existed in common js. Thank you!
0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.