Home > other >  Impossible to require a module in VueJS using require.context although the path is right
Impossible to require a module in VueJS using require.context although the path is right

Time:09-28

I'm trying to require every description.js file in a subfolder. I wrote these lines:

require.context(
      './',
      true,
      /description.js$/,
    ).keys()
    .forEach((k) => {
      console.log(k);
      console.log(`${k.replace('./', '@/components/subfolder/').replace('.js', '')}`)
      console.log('@/components/subfolder/tool/description');
      const path = '@/components/subfolder/tool/description'; // TRY
      const t = require(path); // TRY
      //   const t = require(`${k.replace('./', '@/components/subfolder/').replace('.js', '')}`); // COMMENT 1
      //   const t = require('@/components/subfolder/tool/description'); // COMMENT 2
      console.log(t);
    });

requiring directly using "COMMENT 2" works like a charm, but what I would like is to loop through all the files I want to require, so the "COMMMENT 1" would be great. So, for some reason, it appears that you have to directly write the path in the require. I tried the two lines commented "TRY", and it doesn't work, surprisingly!

Here is the error I get in the console:

Uncaught (in promise) Error: Cannot find module '@/components/subfolder/tool/description'

Can somebody explain how I can dynamically loop through the subfolder?

CodePudding user response:

I found the answer, or at least a working answer:

function importAll(r) {
  r.keys().forEach((key) => {
    outils.value[key] = r(key).details;
  });
}

importAll(require.context(
  './',
  true,
  /description.js$/,
));
  • Related