Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack: Copy JSON-files via file-loader

I am using Webpack's module.loaders and file-loader to copy several js-files when compiling:

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

This works fine for me.
I want to do the same thing with JSON-files:

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

But this time it doesn't do anything.
Why does Webpack make a difference between js- and json-files when using the file-loader?

like image 995
misantronic Avatar asked Oct 31 '22 13:10

misantronic


1 Answers

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

You can copy JSON files via file-loader by adding the following code to you Webpack config:

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

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

So, to copy a JSON file you'll first need to import it, for example:

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

Since file-loader emits a path to the where the file was loader, configFile has the value "/config.json".

Now the contents of the JSON file can be loaded however you like, such as with jsonfile

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

or with Angular's HTTP package

http.get(configFile).map(res => res.json()).catch((error: any): any => {
    // ...
}).subscribe(obj => {
    console.log(obj);
});
like image 75
alan Avatar answered Nov 08 '22 09:11

alan