更新:问题由这个公关修复
要注意问题出现的原因和普通纯JavaScript方法无法解决的原因可能是server.ts正在使用TypeScript和Webpack。查查甘特的答案。并在github上跟踪本期。
我正在使用角/万向起动器作为启动程序。我有一个文件config.json
{
"api": "123"
}当我读config in server.ts时
import * as config from '../config.json';
// const config = require('../config.json'); will be same result
console.log(config);它在航站楼上显示了这一点:
{
"api": "123"
}然而,当我尝试阅读config.api in server.ts时
import * as config from '../config.json';
// const config = require('../config.json'); will be same result
console.log(config.api);它显示了undefined。
这是我的文件夹结构(其他部分与角/万向起动器相同)。
my-app
- config.json
+ src
- server.ts当我启动应用程序时,我使用npm start。
是什么原因造成的?谢谢
发布于 2016-08-17 15:32:16
您的配置文件由webpack内联,因此它遵循ES6模块规范,并将JSON作为字符串返回,而不是像您预期的那样返回一个对象。
你和webpack一起建立服务器是有原因的吗?
发布于 2016-08-17 15:10:43
发布于 2016-08-17 16:15:35
方法1是错误的,因为它与问题配置不匹配。问题中的webpack配置对json文件使用原始加载程序,而这个答案是使用json加载器。
使用方法2
两种方法均用nodejs + webpack进行测试。
方法1
var config = require(__dirname + '/config.json');
console.log(config['api']);方法2
var config = JSON.parse(fs.readFileSync(__dirname + '/config.json', 'utf8'));
console.log(config.api);https://stackoverflow.com/questions/38999316
复制相似问题