skip to Main Content

I’m not a js developer, but need to quickly fix a bit of code in order for it to work.

I have this statement:

const random = require('random');

And the variable is used like this in certain places:

const x = random(0,20);

but on visual studio I get the following error.

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

How do I change the const random = require(‘random’); so it’s dynamic and can be used in cases like:

const x = random(0,20);

If more information is needed, please let me know.

2

Answers


  1. Chosen as BEST ANSWER

    Quickest work-around I've found is this:

    function getRandomInt(max) {
        return Math.floor(Math.random() * max);
    };
    

    Math is built-in to JS, so instead I used that to have the same output.


  2. The error message you received indicates that you’re trying to use an ES module (random.module.js) with the require() function, which is typically used in CommonJS modules. This is not supported because ES modules have a different syntax and module system compared to CommonJS.

    To resolve the issue, you can make use of dynamic imports, which are supported in CommonJS modules. Here’s how you can modify your code:

    Instead of using require(‘random’), you can switch to using dynamic imports with the import() function. Here’s an example:

    const randomPromise = import('random');
    
    randomPromise.then(random => {
      const x = random.default(0, 20);
      // Rest of your code that uses 'x'
    }).catch(error => {
      console.error('Failed to import "random" module:', error);
    });
    

    In the code above, import(‘random’) returns a promise that resolves to the random module. You can then use .then() to access the random module and perform the necessary operations.

    Note that the random module may have a default export (random.default) or specific named exports depending on its implementation. Adjust the access to the module accordingly.

    Keep in mind that dynamic imports are asynchronous, so you need to handle the promises appropriately. If you need to use the x variable in multiple places, make sure to wrap the code in functions or use async/await to ensure proper control flow.

    By using dynamic imports, you should be able to resolve the ERR_REQUIRE_ESM error and continue with your code execution successfully.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search