0

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.

a Learner
  • 4,944
  • 10
  • 53
  • 89

1 Answers1

2

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
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17