bestsource

JSON 파일을 TypeScript 파일로 Import하는 방법

bestsource 2023. 2. 28. 23:40
반응형

JSON 파일을 TypeScript 파일로 Import하는 방법

Angular Maps를 사용하여 지도 애플리케이션을 만들고 있는데 위치를 정의하는 마커 목록으로 JSON 파일을 가져오고 싶습니다.이 JSON 파일을 app.component.ts 내의 marker[] 배열로 사용하고 싶습니다.TypeScript 파일 내에 마커의 하드 코드 배열을 정의하는 대신

프로젝트에서 사용하기 위해 이 JSON 파일을 Import하는 가장 좋은 프로세스는 무엇입니까?어떤 방향이든 감사합니다!

Aonepathan의 원라이너는 최근 타이프 스크립트가 업데이트되기 전까지 나를 위해 작동했다.

Jecelyn Yeen의 투고를 찾았습니다.이 투고는 TS Definition 파일에 이 스니펫을 투고하는 것을 제안합니다.

파일 " " "typings.d.ts합니다.

declare module "*.json" {
    const value: any;
    export default value;
}

그런 다음 다음과 같이 데이터를 가져옵니다.

import * as data from './example.json';

2019년 7월 갱신:

Typescript 2.9 (docs)는 보다 스마트하고 뛰어난 솔루션을 도입했습니다.순서:

  1. resolveJsonModule의 이 합니다.tsconfig.json 일::
"compilerOptions": {
    ...
    "resolveJsonModule": true
  }

import 스테이트먼트는 디폴트 내보내기를 상정할 수 있습니다.

import data from './example.json';

이제 인텔리센스가 json 파일을 체크하여 Array 등의 메서드를 사용할 수 있는지 확인합니다.대단합니다.

Reddit 투고에서 설명한 바와 같이 Angular 7 이후에는 다음 2단계로 작업을 간소화할 수 있습니다.

  1. 세 을 더하면 됩니다.compilerOptions 안에서tsconfig.json 삭제:
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
  1. json 데이터 가져오기:
import myData from '../assets/data/my-data.json';

이치노 해서 '어울리지 않다'를 할 수 되었습니다.myData컴포넌트/서비스로 이행합니다.

입력해 주신 분들 덕분에 수정을 찾을 수 있었습니다.app.component.ts 파일 위에 json을 추가하고 정의했습니다.

var json = require('./[yourFileNameHere].json');

이는 최종적으로 마커를 생성하며 단순한 코드 행입니다.

다음은 @ryanrain 답변에 기초한 Angular 6+의 완전한 답변입니다.

angular-cli 문서에서는 json을 자산으로 간주하고 표준 Import에서 액세스하여 ajax 요청을 사용할 수 없습니다.

json 파일을 "your-json-dir" 디렉토리에 추가한다고 가정합니다.

  1. angular.json 파일에 "your-json-filename"을 추가합니다(:

    "assets": [ "src/assets", "src/your-json-dir" ]

  2. 프로젝트 루트에서 typings.d.ts 파일을 작성 또는 편집하고 다음 내용을 추가합니다.

    declare module "*.json" { const value: any; export default value; }

    이를 통해 ".json" 모듈을 typescript 오류 없이 가져올 수 있습니다.

  3. 컨트롤러/서비스/기타 파일에서 다음 상대 경로를 사용하여 파일을 Import할 수 있습니다.

    import * as myJson from 'your-json-dir/your-json-file.json';

번째 해결책 - .json 파일의 확장자를 .ts로 변경하고 추가하기만 하면 됩니다.export default다음과 같이 파일의 선두에 표시됩니다.

export default {
   property: value;
}

그런 다음 다음과 같이 타이핑을 추가할 필요 없이 파일을 Import하기만 하면 됩니다.

import data from 'data';

번째 솔루션은 HttpClient를 통해 json을 가져옵니다.

다음과 같이 HttpClient를 컴포넌트에 삽입합니다.

export class AppComponent  {
  constructor(public http: HttpClient) {}
}

다음 코드를 사용합니다.

this.http.get('/your.json').subscribe(data => {
  this.results = data;
});

https://angular.io/guide/http

이 솔루션에는 여기에 나와 있는 다른 솔루션보다 확실한 이점이 있습니다.json이 변경되어도 애플리케이션 전체를 재구축할 필요가 없습니다(다른 파일에서 동적으로 로드되므로 해당 파일만 수정할 수 있습니다).

나는 몇 가지 답변을 읽었지만 그것들은 나에게 효과가 없는 것 같았다.저는 Typescript 2.9.2, Angular 6를 사용하고 있으며 Jasmine Unit Test에서 JSON을 Import하려고 합니다.이게 날 위한 묘기였어

추가:

"resolveJsonModule": true,

로.tsconfig.json

Import like:

import * as nameOfJson from 'path/to/file.json';

이제 그만ng test, 다시 시작합니다.

참고 자료: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/ #json-timeout

Typescript 2.9에서는 다음과 같이 간단히 추가할 수 있습니다.

"compilerOptions": {
    "resolveJsonModule": true
}

에게tsconfig.json그 후 json 파일을 쉽게 사용할 수 있습니다(VShode에서도 좋은 유형의 추론이 있을 것입니다).

data.json:

{
    "cases": [
        {
            "foo": "bar"
        }
    ]
}

Typescript 파일에서 다음을 수행합니다.

import { cases } from './data.json';

각도 10

대신 (이름의 "앱"에 알림) 파일을 편집해야 합니다.

여기 보면,compilerOptions를 추가하기만 하면 됩니다.resolveJsonModule: true.

예를 들어 완전히 새로운 프로젝트의 파일은 다음과 같습니다.

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],
    "resolveJsonModule": true
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

Angular 7+의 경우,

1) "typings.d.ts" 파일을 프로젝트의 루트 폴더에 추가합니다(예: src/typings.d.ts).

declare module "*.json" {
    const value: any;
    export default value;
}

2) JSON 데이터의 Import 및 액세스:

import * as data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data.default);
    }

}

또는 다음과 같이 입력합니다.

import data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data);
    }

}

angular7에서는 간단하게

let routesObject = require('./routes.json');

my routes.json 파일은 다음과 같습니다.

{

    "routeEmployeeList":    "employee-list",
    "routeEmployeeDetail":      "employee/:id"
}

json 항목에 액세스하려면

routesObject.routeEmployeeList

다른 file.json도 Import할 수 없었습니다.하지만 이렇게 해결했다.

const swaggerDoc = require('../swagger.json')
let fs = require('fs');
let markers;
fs.readFile('./markers.json', handleJSONFile);

var handleJSONFile = function (err, data) {
   if (err) {
      throw err;
   }
   markers= JSON.parse(data);
 }

언급URL : https://stackoverflow.com/questions/46991237/how-to-import-json-file-into-a-typescript-file

반응형