json 파일을 가져오는 동안 Typescript 컴파일러 오류 발생
코드는 간단합니다.
calls.json
{"SERVER":{
"requests":{
"one":"1"
}
} }
파일.ts
import json = require('../static/calls.json');
console.log(json.SERVER);
생성된 javascript가 올바르고 노드 js 서버를 실행하면 콘솔로그 json이 생성됩니다.SERVER는 '{ requests: { one: '1' }'을(를) 정상적으로 인쇄합니다.
그러나 typscript 컴파일러(commonjs)는 이 상황을 특별히 좋아하지 않고 "Cannot find module '../static/calls.json"이라고 발음합니다.
물론 다음과 같은 .d.ts 파일을 작성하려고 했습니다.
declare module '../static/calls.json'{
var exp:any;
export = exp;
}
그러면 "주변 모듈 선언에서는 상대 모듈 이름을 지정할 수 없습니다."라는 메시지가 나타납니다.
다음과 같은 다양한 변종도 시도해 보았습니다.
declare module 'calls.json' {
import * as json from '/private/static/calls.json';
export = json;
}
그 후 다음을 요구합니다.
import json = require('calls.json');
정상적으로 동작하는 컴파일러가 없고, 컴파일러 자체의 작은 에러가 있다:)
commonjs serverside와 amd clientside를 사용하고 상수를 로드하기 위해 단일 파일을 사용하기 때문에 외부 .json 파일을 사용합니다.
사용하다var대신import.
var json = require('./calls.json');
모듈이 아닌 JSON 파일을 로드하고 있습니다.import사용해서는 안 됩니다.언제var사용되고 있습니다.require()정상적인 기능처럼 취급됩니다.
Node.js 정의를 사용하는 경우 모든 것이 정상적으로 작동합니다.require정의할 필요가 있습니다.
TS 2.9에서는 올바른 타입의 json Import 지원이 추가되었습니다.추가:
{
"compilerOptions": {
"resolveJsonModule": true
}
}
당신의 안에서tsconfig.json또는jsconfig.json. 다음과 같은 Import:
import json = require('../static/calls.json');
그리고.
import * as json from '../static/calls.json';
해결되어야 하고 올바른 오타가 있어야 합니다!
또 다른 해결책은 변화입니다.data.json로.data.ts이렇게 수출하고 있습니다.
export default {
"key" : {
...
}
}
예상대로 Import:
import { default as data } from './data'
이것은, 다음의 방법으로도 실시할 수 있습니다.importwebpack v2를 사용하는 경우 명령어를 입력합니다.
이것은 비동기적이지 않습니다.
import data from './data.json';//Note that this is not async
또, 고객님의typings.d.tsfile은 다음 와일드카드모듈을 추가하여 다음과 같은 typescript 오류를 방지합니다.Cannot find module
declare module "*.json" {
const value: any;
export default value;
}
관심 있는 분들을 위해asyncImports, 이 문서를 이중으로 확인합니다.
Typescript 2.9부터는 별도의 해킹/로더 없이 JSON 파일을 네이티브로 Import할 수 있습니다.
다음 발췌문은 위의 링크에서 복사한 것입니다.
...이제 TypeScript는 moduleResolution 노드전략을 사용할 때 입력파일로 JSON 파일을 Import할 수 있게 되었습니다.즉, json 파일을 프로젝트의 일부로 사용할 수 있으며, 잘 타이핑됩니다.
./src/settings.json
{
"dry": false,
"debug":
./src/foo.ts
import settings from "./settings.json";
settings.debug === true; // Okay
settings.dry === 2; // Error! Can't compare a `boolean` and `number`
For Angular 6 it can work with simple HTTP get call as below
Service
//interface, could be Array , object
export interface ResultJSON{
}
//Read JSON file for 3DWide
getJSON() {
return this.http.get(this.filepathUrl);
}
Component :import both service and interface and use as below
resultJSON :ResultJSON;
this
.testService
.getJSON()
.subscribe((data: ResultJSON) => {
this.resultJSON= data;
console.log(this.resultJSON);
});
언급URL : https://stackoverflow.com/questions/32950966/typescript-compiler-error-when-importing-json-file
'programing' 카테고리의 다른 글
| 프로바이더에서 $window에 접속하는 방법 (0) | 2023.03.15 |
|---|---|
| 오류: [PrivateRoute]가 컴포넌트가 아닙니다. 의 모든 구성 요소는 또는이어야 합니다. (0) | 2023.03.15 |
| JSON을 설정합니다.NET에서 DataContract/DataMember 속성을 무시합니다. (0) | 2023.03.15 |
| jQuery - .getjson VS .ajax json (0) | 2023.03.15 |
| ERROR 404.3 JSON 파일을 찾을 수 없습니다. (0) | 2023.03.15 |