Webpack: copy JSON files using file loader

I use Webpack module.loaders and file-loader to copy multiple js files when compiling:

 module.loaders = [ { test: /app\/locale\/moment\/.*\.js$/, loader: "file-loader?name=locale/moment/[name].[ext]" } ]; 

This works great for me.
I want to do the same with JSON files:

 module.loaders = [ { test: /app\/locale\/.*\.json$/, loader: "file-loader?name=locale/[name].[ext]" } ]; 

But this time he does nothing.
Why does Webpack make the difference between js and json files when using the file loader?

+3
json javascript webpack
source share
1 answer

This is an adaptation of my answer to my own similar question.

You can copy JSON files through the file loader by adding the following code to your Webpack configuration:

 module: { rules: [ // ... { test: /\.json$/, loader: 'file-loader?name=[name].json' } // ... ] } 

There are two nuances here: 1) the file loader will only copy files that are imported / required somewhere in your code, and 2) the file loader emits the path to where the file was downloaded, and not the contents of the file itself.

So, to copy the JSON file, you first need to import it, for example:

 const configFile = require('../config.json'); 

Since the file loader emits the path to the file where the loader was, configFile is set to "/config.json" .

Now the contents of the JSON file can be downloaded as you like, e.g. jsonfile

 jsonfile.readFile(configFile, function(err, obj) { console.log(obj); }); 

or Angular HTTP package

 http.get(configFile).map(res => res.json()).catch((error: any): any => { // ... }).subscribe(obj => { console.log(obj); }); 
+1
source share

All Articles