[英]How to import a json file using angular and typescript
I am trying to import a local json file into an angular application. 我正在尝试将本地json文件导入有角度的应用程序。 I do not want to use http. 我不想使用http。 I know there are several other questions about this but nothing I have tried seems to work. 我知道与此有关的还有其他几个问题,但我尝试过的任何方法似乎都无效。 I ran npm install typescript to get the latest version. 我运行npm install typescript以获取最新版本。 The file is definitely there because VisualStudioCode gives me a selection list when editing. 该文件肯定存在,因为VisualStudioCode在编辑时会给我一个选择列表。
The data is in the form:- 数据格式为:-
{
"nodes": [
{"id": "Myriel", "group": 1},
{"id": "Napoleon", "group": 1}
],
"links": [
{"source": "Napoleon", "target": "Myriel", "value": 1},
{"source": "Mlle.Baptistine", "target": "Myriel", "value": 8},
{"source": "Mme.Magloire", "target": "Myriel", "value": 10}
]
}
I have tried:- 我努力了:-
import mydata from '../mydata.json';
and 和
import * as mydata from '../mydata.json';
and 和
import {default as mydata} from '../mydata.json';
and 和
import mydata = require('../mydata.json');
with 同
// ./tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
which generally give the compile error cannot find module mydata.json apart from the require() which tells me to use one of the first three I tried. 除了require()告诉我使用我尝试过的前三个方法之一之外,通常会导致编译错误的模块找不到mydata.json模块。
I am using D3 so I have tried 我正在使用D3,所以我尝试了
d3fetch.json("../mydata.json, function(error, data)
which gives the runtime error 404 not found [ http://localhost:4200/mydata.json] 这会导致找不到运行时错误404 [ http:// localhost:4200 / mydata.json]
This MVCE: 该MVCE:
// main.ts
import file from './file.json';
console.log(file);
// file.json
{ "hello": "world" }
// index.d.ts
declare module '*.json' {
const value: any;
export default value;
}
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"esModuleInterop": true,
"resolveJsonModule": true
}
}
Can do this: 可以这样做:
> tsc
> node main.ts
{ hello: 'world' }
Perhaps you should add the json declaration file. 也许您应该添加json声明文件。
I'd also suggest another way: adding the webpack json-loader , and including 'json' to module.exports.resolve.extensions
in webpack.config.json
. 我还建议另一种方法:添加webpack json-loader ,并将'json'包含到module.exports.resolve.extensions
中的webpack.config.json
。
Note that every JSON is a valid JS file - if this file is not use by other entities, you can replace its extension by .js and add export default { "nodes": ...
at the beginning of the file. 请注意,每个JSON都是有效的JS文件-如果其他实体未使用此文件,则可以将其扩展名替换为.js,并在文件的开头添加export default { "nodes": ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.