Search code examples
node.jsangulartypescriptwebpackangular2-universal

Cannot read config.json correctly (TypeScript, Webpack)


UPDATE: the issue is fixed by this PR


Be ware of that the reason that the problem comes out and normal pure JavaScript ways cannot solve it could be because that server.ts is using TypeScript and Webpack. Check Gant's answer. And track this issue on github.

I am using angular/universal-starter as starter. I have a file config.json

{
  "api": "123"
}

When I read config in server.ts:

import * as config from '../config.json';
// const config = require('../config.json');  will be same result
console.log(config);

It shows this in the terminal:

{
  "api": "123"
}

However, when I try to read config.api in server.ts:

import * as config from '../config.json';
// const config = require('../config.json');  will be same result
console.log(config.api);

It shows undefined.

This is my folder structure (other part same like angular/universal-starter).

my-app
  - config.json
  + src
    - server.ts

And when I launch the app, I use npm start.

What may cause this? Thanks


Solution

  • Your configuration file is inlined by webpack, so it follows the ES6 module spec and returns the JSON as a string and not an object as you'd expect from Node.

    Is there a reason you build the server with webpack in the first place?