How do I build a JSON file with webpack?

There is actually a more elegant solution than the one by @user108471 (although it is inspired by it), and that is to use the copy-webpack-plugin. With its transform ability, you can add the desired values to the manifest.json on the fly before copying it to its destination.

It has two advantages:

  • it doesn’t generate an extra unnecessary manifest.js-bundle (@bronson’s solution also fixes this)
  • you don’t need to require the manifest.json in some other .js-file (which would seem semantically backwards to me)

A minimal setup could be this:

webpack.config.js

// you can just require .json, saves the 'fs'-hassle
let package = require('./package.json');

function modify(buffer) {
   // copy-webpack-plugin passes a buffer
   var manifest = JSON.parse(buffer.toString());

   // make any modifications you like, such as
   manifest.version = package.version;

   // pretty print to JSON with two spaces
   manifest_JSON = JSON.stringify(manifest, null, 2);
   return manifest_JSON;
}


module.exports = {

   // ...

   plugins: [
      new CopyWebpackPlugin([
         {
            from: "./src/manifest.json",
            to:   "./dist/manifest.json",
            transform (content, path) {
                return modify(content)
            }
         }])
   ]

}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)