javascript - How can I automatically load all JSON files from a given directory in Webpack? -


edit: there an existing question loading multiple files not adequately address how combine json files single object. see answer below. question not duplicate.


i have directory 100 or json files want load js app, bundled via webpack.

i go through initial pain of writing out 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 rather grab automatically don't have update code when add/remove json files directory in future. how can this?

another question details how load multiple dependencies, had add code combine json files single object. working solution:

// filename only. // example: './foo.json' becomes 'foo' function getfilenameonly(filepath) {   return filepath.split('/').pop().split('.').shift(); }  // 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'}" 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -