Configuring Angular via JSON file using Webpack

My Angular application is configured with a JSON file. I downloaded it through an HTTP GET, but recently decided to enable it directly by adding JSON support to TypeScript with a definition file:

declare module "*.json" { const value: any; export default value; } 

And then import it where necessary:

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

This works great; config is the JSON object itself.

The problem is that I am contacting Webpack, and I want the JSON file to be in the package, but not to be associated with anything else, i.e. config.json should be its own file in the package, and not be bundled with others files.

I tried to do this with file-loader and move-file-loader :

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

This prevents the JSON file from combining and puts it where I want it in the package, but also makes config relative path to the JSON file, i.e. "./config.json" , not the JSON object itself.

Any thoughts on why this might be?

0
json javascript angular webpack typescript
source share
1 answer

Apparently, the file loader emits the path to where the file was downloaded, and not the file itself. So

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

creating config on a line containing the file path is the correct behavior.

Regarding move-file-loader, since I use it with json-loader, the contents of the “moved” file are actually the definition of the TypeScript module, and it seems to still load the attached version of the file, not the “copied” version.

These ideas lead me to the following solution: First of all, we copy the JSON files using the file loader in the Webpack configuration:

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

Then we import the file path sent by the file loader using TypeScript require syntax

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

This import method does not require a JSON definition file, which I mention in my question.

Finally, we can upload the file from our path to the file loader via an HTTP GET:

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

where config is the parsed content of the JSON file.

I will not mark this as an answer right away if someone knows how this works without HTTP.

0
source share

All Articles