如何從Webpack中的給定目錄自動加載所有JSON文件? [重復]

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


This question already has an answer here:

這個問題在這里已有答案:

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.

編輯:存在關於加載多個文件的現有問題,但沒有充分解決如何將JSON文件組合到單個對象中的問題。見下面的答案。這個問題不重復。


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

我有一個包含100個左右JSON文件的目錄,我想加載到我的js app中,它通過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?

但我寧願自動抓取所有內容,這樣我將來在添加/刪除JSON文件時不必更新代碼。我怎樣才能做到這一點?

1 个解决方案

#1


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:

另一個問題詳細說明了如何加載多個依賴項,但我不得不添加一些額外的代碼來將我的JSON文件合並到一個對象中。這是工作解決方案:

// 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://www.itdaan.com/blog/2016/11/10/dd17776bce031e8fa1d1c61e9ade7aaa.html



 
  © 2014-2022 ITdaan.com 联系我们: