Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript / webpack : how to concatenate all json files in directory with a custom loop over files

I am building a reactJs bundle with webpack. I am currently trying to concatenate json files into an object to use with i18next. I feel it's simple, I don't want to use overcomplicated solutions.

I have a directory structure like

messages/locale_name/domain_name.json

How can I import all the json files in a regular object in my code ?

So far, I'm struggling at the very beginning as I found suggestions which need to require('fs") but webpack tells me it cannot resolve the fs module and I've seen I can't install it as it is part of default node config.

Some help appreciated.

Thanks !

like image 790
Sébastien Avatar asked May 06 '16 12:05

Sébastien


1 Answers

After a lot of futzing around, it was actually pretty easy. Below is what I ended up with. The key was getting the JSON Loader set up properly.

Install the JSON Loader for Webpack

  1. npm install --save-dev json-loader

Add the JSON Loader to your Webpack loaders

  1. This is required to use context to pull the files in.
  2. Add this to your webpack.config.js loaders { test: /\.json$/, loader: 'json' },
  3. The final might be something like this:
module.exports = {
  entry: './src/app.js',
  output: { path: __dirname, filename: './build/bundle.js' },
  module: {
    loaders: [
      { test: /\.json$/, loader: 'json' }
    ]
  }
}

Use Context to load the files in and save them into an array

in my app.js:

function requireAll( requireContext ) {
  return requireContext.keys().map( requireContext );
}
var modules = requireAll( require.context("./modules", false, /.json$/) );
  1. Where "modules" is a subdirectory from my app.js (./src/modules in my case).
  2. All of the JSON files will be loaded into an array [Object, Object, Object], which I am storing into var modules
like image 121
Jake Avatar answered Nov 12 '22 20:11

Jake