How to use Webpack to combine JSON files from all subdirectories into one?
webpack is not really suited for the use case you have. Many people think that webpack can be a replacement for a build system, but it's just a module bundler, it doesn't handle every task. Specifically:
- webpack traverses
require()
andimport
statements, meaning it needs the modules to be statically defined. It's possible to get around this by writing a plugin or using a file generated from a template, but even if you did that... - webpack would have a hard time combining the JSON files in the way you want. webpack is good at bundling files into some sort of modules system (CommonJS or AMD). What you want is not a bundle containing modules, but a file containing arbitrary contents.
webpack might be able to do these things using some fancy plugins, but it's likely not worth it. In your case, you probably just want to write a Node script. If you want, you can use a plugin like this to run the code before build.
const fs = require('fs');// https://github.com/isaacs/node-globconst glob = require('glob');const output = {};glob('src/**/*.json', (error, files) => { files.forEach((filename) => { const contents = JSON.parse(fs.readFileSync(filename, 'utf8')); Object.assign(output, contents); }); fs.writeFileSync('output.json', JSON.stringify(output));});
Is there a webpack loader that can combine data.json in all subfolders, and output it to output.json?
Use the merge-webpack-plugin.
This is differ from to run the code before build. Because deep webpack integration allow to follow file changes and update results immidiately while hot reloading:
MergePlugin = require("merge-webpack-plugin");module.exports = { module: { rules: [ { test: /\.(json)$/i, use: [ MergePlugin.loader() ] } ] }, plugins: [ new MergePlugin({ search: './src/**/*.json', }) ]}
- if you need only one target file
output.json
for all folders in your project describe them all insearch
param, and that is all - if you need to join separated files for each top level folders (output_A.json, output_B.json ...) then:
- if your do not need to lookup through subfolders try to play with group param with value
[path]
- read more about grouping - if you need to join all files through each folder and its subfolders you need to create multiple plugin instances for each top level folder; but you can group files in each plugin instance by name or by ext (see grouping)
- if your do not need to lookup through subfolders try to play with group param with value
and some more
@dee Please check this plugin https://www.npmjs.com/package/merge-jsons-webpack-plugin
You can pass array of files/patterns as an input and it will emit single file as json.