Reputation: 49814
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
Upvotes: 1
Views: 6977
Reputation: 49814
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 found the problem:
import * as config from '../config.json';
// const config = require('../config.json'); also works
const json = JSON.parse(config); // <- need this line
console.log(json.api); // 123
Upvotes: 1
Reputation: 5092
Method 1 is wrong as it does not match the question configuration. The webpack configuration in question use raw-loader for json file, while this answer is using json-loader.
Use the method 2
Both methods tested with nodejs + webpack.
Method 1
var config = require(__dirname + '/config.json');
console.log(config['api']);
Method 2
var config = JSON.parse(fs.readFileSync(__dirname + '/config.json', 'utf8'));
console.log(config.api);
Upvotes: 1
Reputation: 1062
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?
Upvotes: 3