Git Product home page Git Product logo

merge-jsons-webpack-plugin's Introduction

Merge json files

Merge Json files using this webpack plugin.

For example,it will be useful to merge i18n json files which are in different modules into a single final json files in angular2 or react modules.

Latest version and breaking changes.

  • Breaking changes introduced in latest version 2.0.0, now all values will be overwritten including arrays, earlier behaviour was to concatenate array and overrite literals.Going foward to concatenate either literals or arrays, pass overwrite false as an input, this will concatenate all values in target with source values.

  • This version also fixes compatibility issue with Webpack 5

Usage

Install with npm

npm i merge-jsons-webpack-plugin
var MergeJsonWebpackPlugin = require("merge-jsons-webpack-plugin");
new MergeJsonWebpackPlugin({
    files: ["./jsons/file1.json", "./jsons/file3.json", "./jsons/file2.json"],
    output: {
        fileName: "./dist/result.json",
    },
});

Details

You can specify either files or groupBy under output.

1) By files
If you want to merge group of files use like this.

new MergeJsonWebpackPlugin({
    debug: true,
    files: ["./jsons/file1.json", "./jsons/file3.json", "./jsons/file2.json"],
    output: {
        fileName: "./dist/result.json",
    },
});
Field Name Description
files Array of json files to be merged
output.fileName Name of merged output file ,relative path from output.path entry

2) By Patterns
This plugin uses glob for searching file patterns,please refer glob for usage for sample pattern. You can specify a pattern to pull all the files that satify the particular pattern and output a single json file.

new MergeJsonWebpackPlugin({
    encoding: "ascii",
    debug: true,
    output: {
        groupBy: [
            {
                pattern: "{./jsons/module*/en.json,./jsons/file1.json}",
                fileName: "./dist/en.json",
            },
            {
                pattern: "{./jsons/module*/es.json,./jsons/file2.json}",
                fileName: "./dist/es.json",
            },
        ],
    },
    globOptions: {
        nosort: true,
    },
});
groupBy Array of patterns and corresponding fileNames.
groupBy[].pattern Pattern to search files for. eg: **/en.json will pull all en.json files under current working directory and sub directories
Do not use curly brackets if there is only single pattern to consider pattern:"./node_modules/**/en.json"
Use curly brackets to group more than one pattern together pattern:"{./node_modules/**/en.json,./src/assets/i18n/en.json}"
groupBy[].fileName output file name for the corresponding pattern.Relative path from output.path entry

3) Run time files

Files generated at run time can also be specified as input to the pattern.The plugin will lookup in the compilation.assets of webpack and try to load it for processing.

Options

key Description.
debug if true, logs will be enabled, by default debug is false.
encoding Optional, encoding to be used default is utf-8.
globOptions Optional, glob options to change pattern matching behavior.
prefixFileName Optional. If true, file names will be prefixed to each file content and merged with outfile

By default, the generated prefix is ​​simply the filename without the .json extension. If you want to customize the process of generating prefixes, you can pass a function as this option. The function should take exactly one argument (the file path) and returns the prefix.
space Optional. A String or Number object that's used to insert white space into the output JSON file for readability purposes. See space parameter description on MDN for details.
duplicates Default value is false.If true, keys at same heirarchy will be preserved in an array, check example.
overwrite Default true, if false values(for same keys) at same heirarchy will be preserved in an array. Check example, issue #31, issue #63 .

Change Logs

Version Changes
1.0.8 Error handling improved. Now fileName is relative path to output path specified
1.0.10 File watching feature added, result will be automatically refreshed if json files are modified
1.0.11 Publish issues with previous version
1.0.12 Added glob options handling
1.0.13 When using groupBy,fixed issue of compilation more than once, added capability to read dynamically generated files,and conditional logging
1.0.14 Webpack 4 breaking changes fix
1.0.15 prefixFileName option added, for feature request #31
1.0.16 Webpack 4 compatibile api changes
1.0.17 Filex extension check removed,file can be of any extention as long as content is json.Testcases also added
1.0.18 Bom issue fix #22
1.0.19 Support for custom "prefixFileName" function
1.0.20 Output formatting via space parameter added, preserving duplicates in an array if duplicates:true instead of overriding existing value.
2.0.0-alpha Breaking Changes Webpack 5 compatibility update, removed duplicates option, instead added overwrite with default value true, this will break existing behaviour of concatination in case of an array, instead now by default overwrites array value in target object.
2.0.0 Json processing moved to compilation hook additionalAssets and changed to sync to fix issue #68

Sample

To see sample you can navigate to example folder. From the root folder merge-jsons-webpack-plugin, you can start the sample application as mentioned below


   > npm install
   > npm start

Access the web application at

 http://localhost:8080

References

merge-jsons-webpack-plugin's People

Contributors

aarthishuba avatar eugenegarbuzovpublic avatar tettusud avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

merge-jsons-webpack-plugin's Issues

Duplicated webpack compile logs

When I upgraded plugin from 1.0.7 to 1.0.8 duplicated entries started to show on console.

Hash: 12af48d7fdaba0bddfd9
Version: webpack 3.5.2
Time: 8391ms
...
Hash: 12af48d7fdaba0bddfd9
Version: webpack 3.5.2
Time: 8679ms
...
Hash: 12af48d7fdaba0bddfd9
Version: webpack 3.5.2
Time: 8957ms
...

It looks that number of duplicated logs is equal to number of objects in groupBy array defined in wepack config.

    new MergeJsonWebpackPlugin({
      output: {
        groupBy: [{
          pattern: './app/**/i18n/*-en_US.json',
          fileName: './dist/res/i18n/locale-en_US.json'
        }, {
          pattern: './app/**/i18n/*-de_DE.json',
          fileName: './res/i18n/locale-de_DE.json'
        }, {
          pattern: './app/**/i18n/*-de_DE.json',
          fileName: './dist/res/i18n/locale-de_DE.json'
        }]
      }
    })

Files watcher

I'm wondering if it is possible to add a watcher to track any changes in json and rewrite output file.

Unable to merge json's

Not sure if am doing it right. I wrote this code in webpack.config.js 's plugin section

var MergeJsonWebpackPlugin = require("merge-jsons-webpack-plugin");
new MergeJsonWebpackPlugin({
"files": [
"./jsons/file1.json",
"./jsons/file3.json",
"./jsons/file2.json"
],
"output": {
"fileName": "./dist/result.json"
}
});

After that ran ionic serve
but RESULT.json was never created with merged JSON data

P.S This is for Ionic4 project where we are trying to merge language JSON's using pattern

Compatibility with webpack 1?

Hi!

Using webpack 1 for a project and I cannot seem to get the merge of the files to work.
I have tried all kinds of paths.

output: {
path: path.join(root, 'public'),
filename: '[name].js',
publicPath: '/'
},
plugins: [
new MergeJsonWebpackPlugin({
"debug": true,
"output": {
"groupBy": [
{
"pattern": "src/language/en/categories/buttons.json",
"fileName": "src/language/en/index.json"
}
]
},
"globOptions":{
"nosort": true
}
}),

This outputs:
$ NODE_ENV=development DEBUG=gfw:* node webpack/server
-> Listening at http://0.0.0.0:3000
MergeJsonsWebpackPlugin emit started...
MergeJsonsWebpackPlugin emit completed...
MergeJsonsWebpackPlugin after-emit starts...
MergeJsonsWebpackPlugin after-emit completed...
webpack built 5f6efad35c33ce9779e7 in 13152ms

+++++++++++++++++++++++++++++++++++++++++++++++++++
new MergeJsonWebpackPlugin({
"debug": true,
"files": [
"src/language/en/categories/buttons.json",
"src/language/en/categories/reports.json",
"src/language/en/categories/general.json"
],
"output": {
"fileName": "src/language/en/index.json"
}
}),

This outputs:
$ NODE_ENV=development DEBUG=gfw:* node webpack/server
-> Listening at http://0.0.0.0:3000
MergeJsonsWebpackPlugin emit started...
MergeJsonsWebpackPlugin emit completed...
MergeJsonsWebpackPlugin after-emit starts...
MergeJsonsWebpackPlugin after-emit completed...
webpack built 5f6efad35c33ce9779e7 in 13152ms

Plugin not working in webpack v5 when moving from v4

According to the docs I have to use overwrite: false to have allow arrays to be combined from several json files. However, also keys with strings gets converted into arrays. I think this is a bug. I would like to have an option to ONLY merge arrays and not keys with the same name. These should instead be overridden. I've downgraded to v1.0.21 to make this behaviour work as expected for webpack 5.

Emitting json files in watch mode when changes are made to other files

Using webpack 4.4.1 and merge plugin 1.0.14 in watch mode.
Whenever I change any file in my project (like css, js or html) and incremental rebuild is triggered, json files are also emitted even if no changes were made to them:

Here is an output whenever i change 1 line of css:

95% emitting unnamed compat plugin
Hash: 3ad65b9c774505a89aaf
Version: webpack 4.4.1
Time: 522ms
Built at: 2018-3-29 19:36:58
Asset Size Chunks Chunk Names
solomoto.css 756 KiB solomoto [emitted] solomoto
solomoto.js 7.75 MiB solomoto [emitted] solomoto
en.json 159 KiB [emitted]
es.json 169 KiB [emitted]
ru.json 168 KiB [emitted]
pt-BR.json 170 KiB [emitted]

Watch is not picking up new files after dev-server started

Hi, I'm working on an Angular application and using the plugin to merge i18n files. It's working great however I've noticed that if I start a dev server ng serve it will detect changes on existing files and re compile but If I add a new json file I have to stop the dev server and re-start it for webpack to watch the new file.

I'm guessing it has something to do with the fact that when a new .json file is created it's blank and that would error out the plugin.

Thanks in advanced.

Dependencies:
"@angular-builders/custom-webpack": "^9.2.0",
"@angular-devkit/architect": ">= 0.900 < 0.1100",
"@angular-devkit/build-angular": "~0.901.1",
"merge-jsons-webpack-plugin": "^1.0.21",

custom-webpack.config.ts

import * as webpack from 'webpack';
import * as MergeJsons from 'merge-jsons-webpack-plugin';

const LANGUAGES = [
    'english',
    'español'
];

export default {
    plugins: [
        new MergeJsons({
            debug: true,
            output: {
                groupBy: LANGUAGES.map((language: string) => {

                    return {
                        pattern: `./src/app/**/${ language }.json`,
                        fileName: `./assets/i18n/${ language }.json`
                    };

                })
            },
            globOptions: {
                nosort: true
            }
        })
    ]
} as webpack.Configuration;

deep merge?

Hi @tettusud,
First of all, thanks for your plugin, it is very useful.

For my app, I need to merge several i18n json files, but internally they may refer to the same root.
e.g.:
validations.i18n.json:
core: { validators: { required: "This field is required" }}
commands.i18n.json:
core: { commands: { ok: "OK", cancel: "Cancel" } }

If I merge that, the Core object is overwritten.
I modified the plugin locally, by adding a function like this:

mergeDeep(target, source) { if (typeof target == "object" && typeof source == "object") { for (const key in source) { if (typeof source[key] == "object") { if (!target[key]) Object.assign(target, { [key]: {} }); this.mergeDeep(target[key], source[key]); } else { Object.assign(target, { [key]: source[key] }); } } } return target; }

Maybe it is useful to you.
Best regard,
Leo

create merged jsons at first

Hi,

Is it possible to create the merged jsons at first? Because I want to use it in combination with HtmlWebpackPlugin and templateParameters.
If I use this line

templateParameters: require('./src/jsons/bundle.json')

I get the message

Error: Cannot find module './src/jsons/bundle.json'

Because the bundle has not been created yet

Unable to merge json files

Hi,

I've created a project with a custom webpack and using Typescript and I'm trying to merge i18n json files into a single one but it is not generating any output.

Here's my Webpack 4 file

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MergeJsonWebpackPlugin = require("merge-jsons-webpack-plugin")
const webpackMerge = require('webpack-merge');
const path = require('path');

const mergeJsonPlugin = new MergeJsonWebpackPlugin({
  "encoding": "ascii",
  "debug": true,
  "output": {
    "groupBy": [
      {
        "pattern": "{./src/components/app/i18n/app-fr.json}",
        "fileName": "./src/i18n/app-fr.json"
      },
      {
        "pattern": "{./src/components/app/i18n/app-en.json}",
        "fileName": "./src/i18n/app-en.json"
      },
    ]
  },
  "globOptions": {
    "nosort": true
  }
});

const loadPresets = require('./build-utils/loadPresets');
const modeConfig = env => require(`./build-utils/webpack.${env}`)(env);

function srcPath(subdir) {
	return path.join(__dirname, './src', subdir);
}

module.exports = ({ mode, presets } = { mode: 'production', presets: [] }) => webpackMerge(
  {
    entry: './src/index.tsx',
    mode,
    output: {
      filename: 'bundle.js',
      publicPath: '/',
    },
    devServer: {
      port: 3000,
      historyApiFallback: true,
    },
    resolve: {
      // Add `.ts` and `.tsx` as a resolvable extension.
      extensions: [".ts", ".tsx", ".js"],
      alias: {
        actions: srcPath('store/actions'),
        reducers: srcPath('store/reducers'),
        components: srcPath('components'),
        store: srcPath('store'),
        types: srcPath('types'),
        actiontypes: srcPath('store/actiontypes'),
      },
    },
    module: {
      rules: [
        {
          test: /\.jpe?g/,
          use: [
            {
              loader: 'url-loader',
              options: {
                limit: 5000,
              }
            }
          ],
        },
      ],
    },
    plugins: [new HtmlWebpackPlugin({
      title: 'Préposé au contenu',
      template: './public/index.html',
      filename: './index.html'
    }), new webpack.ProgressPlugin(), mergeJsonPlugin]
  },
  modeConfig(mode),
  loadPresets({ mode, presets }),
);

Here's the plugin debug output

MergeJsonWebpackPluginMergeJsonsWebpackPlugin emit started...
MergeJsonsWebpackPlugin emit completed...                                                                                                            MergeJsonWebpackPluginMergeJsonsWebpackPlugin after-emit starts...
MergeJsonsWebpackPlugin after-emit completed... 

Am I doing something wrong?

Thank you for your time and effort you put into this plugin.

GroupBy pattern : files are not merged when a space exist in pattern

I faced an issue regarding pattern, when a space exist in the pattern definition :
These groupBy definitions will not work, because of the spaces, after the coma, or at the end of the pattern

groupBy: [
  {
      pattern: '{../../libs/sdk/src/resources/i18n/**/en.json, ./src/resources/i18n/**/en.json}',
      fileName: 'resources/i18n/en.json'
  }
]
groupBy: [
  {
      pattern: '{../../libs/sdk/src/resources/i18n/**/en.json,./src/resources/i18n/**/en.json }',
      fileName: 'resources/i18n/en.json'
  }
]

When writing the pattern, I felt as if it was a json object... when it's not.
Is it possible to define the pattern as a string or an array of string, to avoid this kind of errors ?

groupBy: [
  {
      pattern: ['../../libs/sdk/src/resources/i18n/**/en.json', './src/resources/i18n/**/en.json'],
      fileName: 'resources/i18n/en.json'
  }
]

When using mac terminal, sometimes will generate wrong file.

The json file structure looks like:

  • LevelA.json
  • LevelB.json
  • LevelC.json
  • LevelD.json

Expected result will be LevelB replace LevelA if same key already exists and so on.

Sometimes the plugin will generate wrong file that even not an valid .json format, but sometimes it works as expected.

Wrong file looks like:

{"LevelA":"text1","LevelB","text2","LevelC":"text3","LevelD","text4"}"LevelB": "text2"}

My config is:

		new MergeJsonWebpackPlugin( {
			'debug': false,
			'output': {
				'groupBy': gameConfig.getLocalisationConfig()
			},
			'globOptions': {
				'nosort': true
			}
		} )

I turn on the debug, but didn't found more detail.

Did I miss something?

Add ability group by the same name

Assume, I have locales from different libraries
lib1/locales/.json
lib2/locales/
.json

And I want to merge them the same way as merge-webpack-plugin does with option
group: '[name]',

With this option I do not need to specify each file name in configuration and fully rely on similarity of names in different folders (for example, 'lib1/locales/en_US.json', 'lib2/locales/en_US.json')

Unfortunately merge-webpack-plugin is outdated and does not work with webpack 4

Incompatibility with Webpack 5

I'm not able to run webpack in development mode when source-map is enabled and set to cheap-module-source-map or inline-source-map.
On digging I found out your plugin is not fully compatible with webpack v5 which is causing that issue.
To test:
node --trace-deprecation node_modules/webpack/bin/webpack.js
Output:

(node:14444) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
        Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
        Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
    at MergeJsonWebpackPlugin.addAssets (C:\Users\1gour\OneDrive\Documents\old\Github\Notion-Boost-browser-extension\node_modules\merge-jsons-webpack-plugin\index.js:234:42)
    at C:\Users\1gour\OneDrive\Documents\old\Github\Notion-Boost-browser-extension\node_modules\merge-jsons-webpack-plugin\index.js:38:30
    at tryCatch (C:\Users\1gour\OneDrive\Documents\old\Github\Notion-Boost-browser-extension\node_modules\es6-promise\dist\lib\es6-promise\-internal.js:195:12)   
    at invokeCallback (C:\Users\1gour\OneDrive\Documents\old\Github\Notion-Boost-browser-extension\node_modules\es6-promise\dist\lib\es6-promise\-internal.js:210:13)
    at publish (C:\Users\1gour\OneDrive\Documents\old\Github\Notion-Boost-browser-extension\node_modules\es6-promise\dist\lib\es6-promise\-internal.js:178:7)     
    at flush (C:\Users\1gour\OneDrive\Documents\old\Github\Notion-Boost-browser-extension\node_modules\es6-promise\dist\lib\es6-promise\asap.js:98:5)
    at processTicksAndRejections (internal/process/task_queues.js:76:11)

You can see that webpack config file: https://github.com/GorvGoyl/Notion-Boost-browser-extension/blob/72c0da7202b2cbcd6006d553fe59035abdb8d9e4/webpack.config.js#L217

steps to reproduce:

  • Clone https://github.com/GorvGoyl/Notion-Boost-browser-extension/tree/webpack5_devtool_bug
  • npm install
  • run webpack in development mode npm run start:ch
  • build would fail with above error.

Other relevant information:
webpack version: 5.6.0
Node.js version: 12.15.0
Operating System: Win10
Additional tools: Powershell Core, VSCode

I previously filed this bug for Webpack webpack/webpack#12041

feature request: work with absolute path

Hi,

Could you please consider to implement working with absolute path. (in files, patterns, filenames etc parameters)
I do browser extension development and merge-jsons-webpack-plugin works only in developer mode where I run the extension with webpack-dev-server, but throw an error in production mode, where I have to user absolute paths - lack of any server - to deploy the extension

Thanks

Deep merge with file path

Hello!

Is it possible to do like so:

Your application structure:

/src/app/
|-- catalog
|   |-- catalogItem
|   |   |-- locales
|   |   |   |-- en.json
|   |   |   `-- ru.json
|   |   `-- catalogItem.component.js
|   |-- locales
|   |   |-- en.json
|   |   `-- ru.json
|   `-- catalog.component.js
`-- user
    |-- locales
    |   |-- de.json 
    |   |-- en.json
    |   `-- ru.json
    `-- user.component.js

After using the above gulpfile.js:

/dist/locales/
|-- de.json
|-- en.json
`-- ru.json

The en.json file will look like this:

{
  "catalog": {
    "catalogItem": {
      // contents of `/src/app/catalog/catalogItem/locales/en.json`
    },
    // contents of `/src/app/catalog/locales/en.json`
  },
  "user": {
    // contents of `/src/app/user/locales/en.json`
  }
}

So you can obtain values using dot notation, catalog.catalogItem.headline for example.

Gulp example: https://github.com/loginov-rocks/gulp-locales-bundler/blob/master/src/gulpLocalesBundler.js

postinstall script 'typings install' fails

npm i merge-jsons-webpack-plugin --save

[email protected] postinstall /Users/dominiksteiner/Documents/workspace-broadsoft/hub/hubLib/node_modules/merge-jsons-webpack-plugin
typings install

sh: typings: command not found
....
npm ERR! [email protected] postinstall: typings install
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the [email protected] postinstall script 'typings install'.

Is there some dependency on globally installed typings?

Keep file names as parent object of content in merged files

Hi,
Do you plan to add the possibility to keep file names in result file?

The example:
There are separate i18n files:

sign_in.json

{  
    "submit": "Sign in"
}
sign_up.json

{
    "submit": "Sign up" 
}

I'd like to have following structure of the resulting file:

{ 
    "sign_in": { 
        "submit": "Sign in"
    }, 
    "sign_up": { 
        "submit": "Sign up"
    }
}

Plugin causes [email protected] compiler to compile twice.

Calling the compiler from nodeJS.

  const compiler = webpack(config);
  compiler.run((err, stats) => {
    if (err || stats.hasErrors()) {
       console.log("error when bundling");
       reject(err);
     }
     console.log("File bundling finished.");
     resolve();
   });

If using [email protected] - the merge plugin causes the following output

(node:11694) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.
(node:11694) DeprecationWarning: Chunk.modules is deprecated. Use Chunk.getNumberOfModules/mapModules/forEachModule/containsModule instead.
MergetJsonsWebpackPlugin emit...
File bundling finished.
Tarball created - Webserver Configuration added.
File bundling finished.

Removing merge plugin produces following output:

(node:11655) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.

(node:11655) DeprecationWarning: Chunk.modules is deprecated. Use Chunk.getNumberOfModules/mapModules/forEachModule/containsModule instead.
File bundling finished.
Tarball created - Webserver Configuration added.

The emitted json file is not picked up by subsequent webpack plugins

json file emiited by this plugin is not picked up by other plugins like zip-webpack-plugin or compression-webpack-plugin. It used to work in webpack 4 but not in v5.

Code Snippet:

  const manifest = ["src/manifest.json"];
    manifest.push("src/manifest.chrome.json");

new MergeJsonWebpackPlugin({
      files: manifest,
      output: {
        fileName: "manifest.json",
      },
    }),

new ZipPlugin({ filename: `notion-boost_${browser}.zip` }),
"merge-jsons-webpack-plugin": "^2.0.0-alpha",
"webpack": "^5.14.0",
"zip-webpack-plugin": "^4.0.1"

Array deepMerge function

Hi, I noticed that you use the concat array method in the mergeDeep function to concat both arrays together as a one array
Example:
1.json
{ "numbers": [1,2,3] }
2.json
{ "numbers": [4,5,6] }
The result:
{ "numbers": [1,2,3,4,5,6] }

I think this is the default behavior but I would like to suggest if you can add an option to control if we want to concat the arrays or override the values like this:

1.json
{ "numbers": [1,2,3] }
2.json
{ "numbers": [4,5,6] }
The result:
{ "numbers": [4,5,6] }

Thank you for this amazing plugin.

Merging of files content if prefixFileName = false

Hi there!
Thank you for your plugin. It`s very useful!
But I bumped into a problem. Hope you can help with it
So I have a number of json files in folder and want to merge them

  • parent
    -- child1.json
    -- child2.json
    -- child3.json

When I use prefixFileName = true i`m getting the result as

"parent" : { "child1" : {}, "child2" : {}, "child3" : {} }

But If i do prefixFileName = false data from children is merged (I have to say that data in files is similar)

What is expected: To get an Array of children instead of Object

output file not being generated

Thanks for such an amazing plugin!

For some reason an output file is not being generated for me in my own app as well as the example app you have.

My app:

  plugins: [
    new MergeJsonWebpackPlugin({
      "files": [
        'trimmers/entry1506670635260.json',
        'trimmers/entry1507044430282.json'],
      "output": {
        "fileName":"test.json"
      }
    })
  ]

Webpack runs without any issues, but no test.json file is created for me. I was expecting to see test.json generated in my root, but I'm not seeing anywhere in the application. Am I missing a step?

Thank you

Watch mode?

Does this work in watch mode / dev-server? Having this config:

new MergeJsonWebpackPlugin({
            "output": {
                "groupBy": ["it", "en", "fr"].map(lang => ({
                    "pattern": `**/*.${lang}.json`,
                    "fileName": `${METADATA.isDevServer ? "src" : "wwwroot"}/assets/i18n/${lang}.json`
                }))
            }
        }),

Output files don't look like to be updated when any of the source files change. I need to restart webpack in order to have them updated.

I also tried with --watch-content-base, but it seems ineffective.

`plugin.fileDependencies` grows with each compilation.

It looks like when you concatenate dependencies onto the plugin.fileDependencies array, it is adding these to the saved dependencies from the previous run.

this.fileDependencies = this.fileDependencies.concat(files);

here's some console output:
image

How do I prevent structural changes to the json?

In my source json files I have an array of objects.

`"children": [
    {
      "role": "link",
      "title": "Sub One",
      "routerLink": "/spog-module-seed/sub-one"
    },
    {
      "role": "link",
      "title": "Sub Two",
      "routerLink": "/spog-module-seed/sub-two"
    }
]`

and the result becomes

`"children": {
      "0": {
        "role": "link",
        "title": "Sub One",
        "routerLink": "/spog-module-seed/sub-one"
      },
      "1": {
        "role": "link",
        "title": "Sub Two",
        "routerLink": "/spog-module-seed/sub-two"
      }
}`

is there a way to influence this behavior so the output contains and array of objects?

Webpack doesn't watch my json files for changes

Experimenting using this plugin, I have to restart webpack before it cares about changes to the json files referenced. I'm not a webpack expert. Is there a way the centralised json files can be updated automatically when file changes are detected?

Thank you for your help.

glob options

hey, I was wondering if you would support taking in a globOptions key in options and passing that to the _glob function? My use case is when specifying exact file names, I don't want Glob to auto sort the files because in the merge, order matters. So I'd like to be able to pass use your plugin like so:

new MergeJsonWebpackPlugin({
        output: {
          groupBy: [
            { pattern: '{pathTo/root.json,pathTo/a.json}',
              fileName: '/distPathTo/a.json' },
            { pattern: '{pathTo/root.json,pathTo/b.json}',
              fileName: '/distPathTo/b.json' },
          ],
        },
        globOptions: {
          nosort: true,
        },
      }),

Issue with webpack 4 beta0 and file emitting

I'm having the following error while emmiting merged json files. Im' using webpack 4 beta0 + merge-jsons-webpack-plugin 1.0.13, guess this is a compatibility issue with new webpack version.

95% emitting unnamed compat plugin \node_modules\merge-jsons-webpack-plugin\index.js:67
compilation.fileDependencies.push(f);
^

TypeError: compilation.fileDependencies.push is not a function
at fileDependencies.forEach (\node_modules\merge-jsons-webpack-plugin\index.js:67:54)
at Array.forEach (native)
at compiler.plugin (\node_modules\merge-jsons-webpack-plugin\index.js:64:39)
at AsyncSeriesHook.eval [as callAsync] (eval at create (\node_modules\tapable\lib\HookCodeFactory.js:24:12), :7:1)
at AsyncSeriesHook.lazyCompileHook [as _callAsync] (\node_modules\tapable\lib\Hook.js:35:21)
at asyncLib.forEach.err (\node_modules\webpack\lib\Compiler.js:286:26)
at \node_modules\async\dist\async.js:473:16
at iteratorCallback (\node_modules\async\dist\async.js:1050:13)
at \node_modules\async\dist\async.js:958:16
at \node_modules\graceful-fs\graceful-fs.js:43:10
at FSReqWrap.oncomplete (fs.js:123:15)

npm ERR! Windows_NT 10.0.16299
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "run" "buildDev" "--scripts-prepend-node-path=auto"
npm ERR! node v6.12.3
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE

And here is the config i use:

    plugins: [
        new MergeJsonWebpackPlugin({
            "output": {
                "groupBy": [
                    {
                        "pattern": "Frontend/translations/en/*.json",
                        "fileName": "en.json"
                    },
                    {
                        "pattern": "Frontend/translations/es/*.json",
                        "fileName": "es.json"
                    },
                    {
                        "pattern": "Frontend/translations/ru/*.json",
                        "fileName": "ru.json"
                    },
                    {
                        "pattern": "Frontend/translations/pt-BR/*.json",
                        "fileName": "pt-BR.json"
                    }
                ]
            }
        })
    ]

watch change does not work

I checked the other ticket (especially #11) but can't get it working on my project.

To eliminate possibilities of misusage on my project, I test as following :

  • clone your repo
  • run npm install in main directory
  • go in example directory and run npm install
  • change the package.json to add --watch-content-base to the start script
  • run npm run start
  • modify the json, it does not compile automatically, you must do npm run webpack to get the result file updated

Am I missing something ?

Can't manage to get the result file generated and saved

Hi, I'm having some trouble to get the proper merged json file created and saved within my project. The base structure is as follows:

-TestApp
  -e2e
  -node_modules
  -src
      -app
      -assets
      -enviornments
  -dist
       [empty]
  -jsons
      *test1.json
      *test2.json
      *test3.json
   ...
  *webpack.config.json

While the plugin config is defined like:

"plugins": [
    new MergeJsonWebpackPlugin({
      "debug": true,
      "files": [
        "./jsons/test1.json",
        "./jsons/test2.json",
        "./jsons/test3.json"
      ],
      "output": {
        "fileName": "./dist/result.json"
      }
    }),

If I npm start the project (which will run webpack-dev-server --port=4200) then I console log the response from the processFiles method in the plugin then I actually get the content of the meant file to be written, but its never saved.

Response {
  filepath: './dist/result.json',
  content: '{"HELLO":"hello world","SOMETHING":"this is something","TESTING":"this is just a test"}' 
}

Also, the console output shows something regarding the file

            Asset            Size        Chunks             Chunk Names
     ...
     ./dist/result.json   87 bytes               [emitted]
     ...

I've also tryed some other configurations with no success such as;

"plugins": [
    new MergeJsonWebpackPlugin({
      "debug": true,
      "output": {
        "groupBy": [
          {
            "pattern": "./jsons/*.json",
            "fileName": "./dist/result.json"
          }
        ]
      }
    }),

Is this an issue from the plugin? I'm doing something wrong on config? Thanks.

Getting file not found for Dynamic Generated files

I am using webpack-angular-translate plugin to dynamically generate a json file (say A.json) and then merge it with an existing json (say B.json).

I get ERROR in MergeJsonWebpackPlugin: MergeJsonWebpackPlugin: Unable to locate file A.json

Is it possible to merge the files from compilation.assets?

I tried with the following change to readFile and it worked for me
nishantkagrawal@e4afddc

Option to handle comments in JSON

I'd like to have an option (or by default) that handles comments in JSON files.

i.e.)

{
  // Comments here...
  "foo": "foo"
}

Thanks for making an awesome plugin!

Error - "Callback was already called."

When I try to compile two files separately, just as you illustrate in the README, it fails with the following error:
image

    plugins: [
        new MergeJsonWebpackPlugin({
            'output': {
                'groupBy': [
                    {
                        'pattern': '{./src/**/translations/en.json, ./src/translations/en.json}',
                        'fileName': 'assets/translations/en.json'
                    },
                    {
                        'pattern': '{./src/**/translations/fr.json, ./src/translations/fr.json}',
                        'fileName':'assets/translations/fr.json'
                    }
                ]
            }
        })
    ]

It works for either the fr.json or the en.json files but not when both are in there.
Angular version: 5.1.2
Merge-json Version 1.0.12

Dev mode support

It seems that in dev mode that the merged json file doesn't get updated after making changes to the input json files. I can see the merge plugin re-running, but it's as if it's operating on a cache of the files or something b/c the output file does not include the updated data.

Is this what you would expect?

Here's my config:

new MergeJsonWebpackPlugin({
      output: {
        groupBy: [
          {
            pattern: "**/*.loc.json",
            fileName:"./localization/en/translations.json"
          }
        ]
      }
    })

Previous content overwritten instead of added to

I have a pattern of language specific folders (/src/i18n/en,/src/i18n/es, etc) that I am matching to find files under each and merge them, but using the following code, the output file only contains the last language. I realize this is probably because inside each language file the structures are the same, ie:

{ "helloMsg": "hello" } and { "helloMsg": "hola" }

instead of

{ "en": { "helloMsg": "hello"} } and { "es": { "helloMsg": "hola"} }

Is there a way for this plugin to write the pattern name of the folder into each grouping before writing it to the file? My translation software unfortunately seems to need me to keep the pattern above for it to be able to write those files to the folders properly.

Below is what my current code looks like

new MergeJsonWebpackPlugin({
            "debug": true,
            "output": {
              "groupBy": [
                  {
                      "pattern": "./src/i18n/*/item-specific/ThisItem.json",
                      "fileName": "./src/i18n/compiled/ThisItem.json"
                  },
                  {
                      "pattern": "./src/i18n/*/item-specific/ThatItem.json",
                      "fileName": "./src/i18n/compiled/ThatItem.json"
                  },
              ]
            },
            "globOptions": {
                "nosort": true
            }
          })

Merged json files seem to be minified per default

When merging two json files a and b the resulting merged json file c seems to be minified although I am in a development environment. Is there an option I can set to configure whether the resulting json file should be minified or not?
If not this would be a really nice feature to implement in a future version.

json files not generating

I'm trying to merge all json files into one for vue-i18n

this is my vue.config.js

...
configureWebpack: {
    plugins: [
      new MergeJsonWebpackPlugin({
        'debug': true,
        'output': {
          'groupBy': [
            {
              'pattern': 'src/locales/nl/*.json',
              'fileName': 'src/locales/nl.json',
            },
          ],
        },
        'globOptions': {
          'nosort': true,
        },
      }),
    ],
  },
...

resulting in

> vue-cli-service serve

MergeJsonWebpackPlugin :: {
  "debug": true,
  "encoding": "utf8",
  "overwrite": true,
  "output": {
    "groupBy": [
      {
        "pattern": "src/locales/nl/*.json",
        "fileName": "src/locales/nl.json"
      }
    ]
  },
  "globOptions": {
    "nosort": true
  }
}
 INFO  Starting development server...
MergeJsonWebpackPlugin :: Running apply() ::::::
98% after emitting CopyPlugin

 ERROR  Failed to compile with 1 error                                                                                                                                                                                      10:24:58

This dependency was not found:

* @/locales/nl.json in ./src/plugins/i18n.js

To install it, you can run: npm install --save @/locales/nl.json

How can I make sure this file is generating?
And am I using this plugin correctly?

Pattern does not find files

Deriving from 2nd example "2) By Patterns" I've created my config:
new MergeJsonWebpackPlugin({ "encoding": "ascii", "debug": true, "output": { "groupBy": [ { "pattern": "{./**/translations/*.en.json}", "fileName": "./assets/locale/en.json" }, { "pattern": "{./**/translations/*.fr.json}", "fileName": "./assets/locale/fr.json" } ] }, "globOptions": { "nosort": true } })

The output files are both empty using these patterns. But when I added , resulting in
"pattern": "{./**/translations/*.en.json,}",
"pattern": "{./**/translations/*.fr.json,}".
It started to work, seems like some object parsing bug :)

Issues when merging with wrong encoding

It seems that UTF-8 encoding works properly, but with other encodings I'll get errors that invalid characters have been encountered in line 0 position 0, even though that is a { for me.

encodin utf8 logs

In version 1.0.7 a lot of encodin utf8 logs are displayed on console.
It looks like this.

...
encodin  utf8
encodin  utf8
encodin  utf8
encodin  utf8
encodin  utf8
...

WebPack 2

This plugin is compatible with WebPack 2 ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.