Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import all files from directory and map file name into array

I currently have this set up with Vue and Webpack:

const imports = {
  foo: require('./folder/foo.yml'),
  bar: require('./folder/bar.yml')
}

Is there a way to add more keys + values with this structure dynamically, where the key equals the file name without the file extension?

like image 413
Doge Avatar asked Jan 22 '26 18:01

Doge


1 Answers

Please see if this helps.

const testFolder = './tests/';
const fs = require('fs');

const imports = {}

fs.readdirSync(testFolder).forEach(file => {
    const filekey = file.split('.').slice(0, -1).join('.');
    imports[filekey] = require('./tests/' + file);
  });
like image 182
Sreeragh A R Avatar answered Jan 25 '26 08:01

Sreeragh A R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!