Skip to content Skip to sidebar Skip to footer

Configuring Angular Via A Json File With Webpack

My Angular app is configured with a JSON file. I was loading it via an HTTP GET, but recently decided to include it directly by adding JSON support to TypeScript with a Definition

Solution 1:

Apparently file-loader emits a path to where the file was loaded, rather than the file contents itself. So

import * as config from'../config.json';

making config into a string containing a path to the file is the correct behavior.

As far as move-file-loader is concerned, since I'm using it with json-loader, the contents of the "moved" file is actually a TypeScript module definition, and it seems to still be loading a bundled version of the file rather than the "copied" version.

These insights lead me to the following solution: First of all, we'll copy JSON files using file-loader in the Webpack config:

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

Then we'll import the file path emitted by file-loader using TypeScript's require syntax

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

This import method doesn't require the JSON definition file I mention in my question.

Lastly, we can load the file from its file-loader path via an HTTP GET:

http.get(configFile).map(res => res.json()).catch((error: any): any => {
    // ...
}).subscribe(config => {
    // ...
});

where config is the parsed contents of the JSON file.

I won't mark this as the answer right away in case someone knows how to get this working without HTTP.

Post a Comment for "Configuring Angular Via A Json File With Webpack"