如何自动从Webpack中的给定目录加载所有JSON文件? [英] How can I automatically load all JSON files from a given directory in Webpack?

查看:75
本文介绍了如何自动从Webpack中的给定目录加载所有JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关加载多个文件的现有问题,但没有充分解决如何将JSON文件组合到单个对象中的问题.请参阅下面的答案.这个问题不是重复的.

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.

我有一个目录,其中包含约100个要加载到我的js应用程序中的JSON文件,该文件通过WebPack捆绑在一起.

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'),
];

但是,我宁愿自动抓取所有内容,以免将来在将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?

推荐答案

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

这篇关于如何自动从Webpack中的给定目录加载所有JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆