Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can require() statement in commonjs be dynamic?

Is require() statement in commonjs module system static or dymanic?
Can require() be dynamic? Can anyone give examples for this?

is following code dynamic or static:

let c1="./c"
let c2=".js";
const f=require(c1+c2);

console.log(f);

I mean will c1+c2 resolved at compile time or run time?
I am totally confused with AI answers. Some time it is saying require() is dynamic sometimes it is saying it is static. Still Stackoverflow is best resource.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s dynamic, but a module is executed only once like in ESM. It’s like a sync version of ESM’s import():

let count = 10;
while (count--) {

    const random = ['fs', 'fs2'][Math.floor(Math.random() * 1.9999)];
    console.log('require', random);

    try {
        const fs = require(random);
    } catch (e) {
        console.log(e.message);
    }
}

Each time this throws an error randomly:

require fs2
Cannot find module 'fs2'
Require stack:
 - /bytex/change-color/test.js
require fs
require fs
require fs2
Cannot find module 'fs2'
Require stack:
 - /bytex/change-color/test.js
require fs2
Cannot find module 'fs2'
Require stack:
 - /bytex/change-color/test.js
require fs2
Cannot find module 'fs2'
Require stack:
 - /bytex/change-color/test.js
require fs2
Cannot find module 'fs2'
Require stack:
 - /bytex/change-color/test.js
require fs
require fs2
Cannot find module 'fs2'
Require stack:
 - /bytex/change-color/test.js
require fs2
Cannot find module 'fs2'
Require stack:
 - /bytex/change-color/test.js
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading