How can I automatically load all JSON files from a given directory in Webpack? [duplicate]

懵懂的女人 提交于 2021-01-23 10:59:11

问题


Edit: There is an existing question about loading multiple files but does not adequately address how to combine JSON files into a single object. See answer below. This question is not a duplicate.


I have a directory with 100 or so JSON files that I want to load into my js app, which is bundled via WebPack.

I could go through the initial pain of writing out the following:

let data = [
    require('json!./Mocks/0.json'),
    require('json!./Mocks/1.json'),
    // 2 - 98...
    require('json!./Mocks/99.json'),
    require('json!./Mocks/error.json'),
    require('json!./Mocks/foo.json'),
];

But I would much rather grab everything automatically so that I don't have to update my code when I add/remove JSON files to that directory in the future. How can I do this?


回答1:


Another question details how to load multiple dependencies, but I had to add some extra code to combine my JSON files into a single object. This is the working solution:

// Get filename only.
// Example: './foo.json' becomes 'foo'
function getFileNameOnly(filePath) {
  return filePath.split('/').pop().split('.').shift();
}

// ALL THE JSON!
function loadJson() {
  const requireContext = require.context('json!./Mocks', false, /\.json$/);
  const json = {};
  requireContext.keys().forEach((key) => {
    const obj = requireContext(key);
    const simpleKey = getFileNameOnly(key);
    json[simpleKey] = obj;
  });
  return json;
}

Usage example:

// ./Mocks/99.json
{
    "name": "ninety nine"
}


// ./Mocks/foo.json
{
    "name": "bar"
}

// App.js
let myJson = loadJson();
console.log(myJson['99']);  // > "Object{name:'ninety nine'}"
console.log(myJson['foo']); // > "Object{name:'bar'}"


来源:https://stackoverflow.com/questions/40532230/how-can-i-automatically-load-all-json-files-from-a-given-directory-in-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!