Webpack: Copy JSON-files via file-loader

后端 未结 1 382
执笔经年
执笔经年 2021-01-21 04:13

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

module.loaders = [
    { test: /app\\/loc         


        
相关标签:
1条回答
  • 2021-01-21 04:22

    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);
    });
    
    0 讨论(0)
提交回复
热议问题