且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何自动从Webpack中的给定目录加载所有JSON文件?

更新时间:2023-11-10 21:45:46

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

用法示例:

// ./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'}"