简体   繁体   中英

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?

You could use Array#reduce to build such an object, example :

 var require = n => n; var imports = ['foo', 'bar', 'baz', 'bat'].reduce((acc, val) => { acc[val] = require(`./folder/${val}`); return acc; }, {}) console.log(imports);

The values in the array could come from something like fs.readdirSync , so we would have for instance :

const ymlFiles = fs.readdirSync('./folder')
  .filter(filename => filename.split('.').reverse()[0] === 'yml');
const ymlFilesNoExt = ymlFiles.map(filename => filename.replace(/\.yml$/, ""))
const imports = ymlFilesNoExtvar require = n => n;
var imports = ['foo', 'bar', 'baz', 'bat'].reduce((acc, val) => {
  acc[val] = require(`./folder/${val}`);
 return acc;
}, {});

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);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM