sourcetip

TypeScript에서 JSON 파일 가져오기

fileupload 2023. 4. 3. 21:42
반응형

TypeScript에서 JSON 파일 가져오기

I have a 나는 가지고 있다JSON file that looks like following: 다음과 같은 파일이 있습니다.

{

  "primaryBright":    "#2DC6FB",
  "primaryMain":      "#05B4F0",
  "primaryDarker":    "#04A1D7",
  "primaryDarkest":   "#048FBE",

  "secondaryBright":  "#4CD2C0",
  "secondaryMain":    "#00BFA5",
  "secondaryDarker":  "#009884",
  "secondaryDarkest": "#007F6E",

  "tertiaryMain":     "#FA555A",
  "tertiaryDarker":   "#F93C42",
  "tertiaryDarkest":  "#F9232A",

  "darkGrey":         "#333333",
  "lightGrey":        "#777777"
}

I'm trying to import it into a 로 Import하려고 합니다..tsx파일. 이 유형 정의에 추가되었습니다.이를 위해 유형 정의에 다음을 추가했습니다.

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

그리고 이렇게 수입하고 있습니다.

import colors = require('../colors.json')

And in the file, I use the color 그리고 그 파일에는 제가 색깔로primaryMain as ~하듯이colors.primaryMain. 하지만 오류가 발생했습니다. 러 시 however됩 i get:표다 an니?

유형 '*.json'의 'type'에 'primaryMain' 속성이 없습니다.

TypeScript 2.9.+ 에서는, 다음의 조작으로 JSON 파일을 간단하게 Import 할 수 있습니다.

import colorsJson from '../colors.json'; // This import style requires "esModuleInterop", see "side notes"
console.log(colorsJson.primaryBright);

은 꼭 에 해 주세요.compilerOptionstsconfig.json(정보):

"resolveJsonModule": true,
"esModuleInterop": true,

사이드 노트:

  • Typescript 2.9.0에는 이 JSON 기능에 오류가 있으며 2.9.2로 수정되었습니다.
  • "interop" colorsJson" Import" 기본 합니다..import * as colorsJson from '../colors.json'

Import 폼과 모듈 선언은 모듈의 모양과 내보내기 내용에 대해 일치해야 합니다.

쓸 때(호환성이 있는 모듈see note 형식을 대상으로 하는 경우 TypeScript 2.9 이후 JSON을 Import하기 위한 차선책)

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

, 은 지정자가 ..json라는 이름의 단일 수출품이 있다 default.

이러한 모듈을 올바르게 소비하는 방법에는 다음과 같은 몇 가지가 있습니다.

import a from "a.json";
a.primaryMain

그리고.

import * as a from "a.json";
a.default.primaryMain

그리고.

import {default as a} from "a.json";
a.primaryMain

그리고.

import a = require("a.json");
a.default.primaryMain

이며, 가 "JavaScript", "JavaScript", "JavaScript"를 갖는 바로 그 입니다.default★★★★★★ 。

그러나 나는 무엇이 잘못되고 있는지에 대한 힌트를 주기 위해 다른 양식을 언급했습니다.마지막 한 가지만 특별히 신경 쓰세요. require는 내보낸 바인딩이 아닌 모듈 자체를 나타내는 객체를 제공합니다.

그럼 왜 오류일까요?당신이 썼기 때문에

import a = require("a.json");
a.primaryMain

하 named named named named named named named named named named named named named라는 이름의 수출품은 .primaryMain에 되었습니다."*.json".

것은 을 JSON R&로 제공하는 로 하고 .default이치노

주의: TypeScript 2.9 이후로는 컴파일러 플래그를 사용하여 Import된 TypeScript를 분석할 수 있습니다..json와일드카드 모듈 선언의 필요성과 파일 존재의 검증을 피하기 위해 파일 형상에 대한 올바른 정보를 제공합니다.이것은 특정 타깃모듈 형식에서는 지원되지 않습니다.

런타임에 json 파일을 가져오는 방법은 다음과 같습니다.

import fs from 'fs'
var dataArray = JSON.parse(fs.readFileSync('data.json', 'utf-8'))

이렇게 하면 큰 파일을 가져올 때 TSC가 느려지거나 메모리가 부족해지는 문제를 방지할 수 있습니다. 이는 resolveJsonModule을 사용할 때 발생할 수 있습니다.

타이프 스크립트 버전 2.9+를 사용하기 쉽습니다.따라서 @kentor descriptioned대로 JSON 파일을 쉽게 Import할 수 있습니다.

그러나 이전 버전을 사용해야 하는 경우:

JSON 타입 스크립트 선선, 로운 your 를 확인합니다.typings.d.ts는 '동일하다'와.include your의 tsconfig.jsonfilename을 클릭합니다.

include 속성을 포함합니다.tsconfig.json 폴더 구조는 다음과 같습니다.

- app.ts
+ node_modules/
- package.json
- tsconfig.json
- typings.d.ts

, ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.include your의 tsconfig.json:

{
    "compilerOptions": {
    },
    "exclude"        : [
        "node_modules",
        "**/*spec.ts"
    ], "include"        : [
        "src/**/*"
    ]
}

당신의 ★★★★★★★★★★★★★★★★★.typings.d.ts에 있어야 합니다.src( 「」에 기재)include

+ node_modules/
- package.json
- tsconfig.json
- src/
    - app.ts
    - typings.d.ts

대부분의 응답에서와 같이 모든 JSON 파일에 대한 글로벌 선언을 정의할 수 있습니다.

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

좀 더 타이핑된 버전을 선호합니다. 설정 합시다.config.json다음과 같이 합니다.

{
    "address": "127.0.0.1",
    "port"   : 8080
}

다음으로 특정 유형을 선언할 수 있습니다.

declare module 'config.json' {
    export const address: string;
    export const port: number;
}

타이프스크립트 파일로 쉽게 가져올 수 있습니다.

import * as Config from 'config.json';

export class SomeClass {
    public someMethod: void {
        console.log(Config.address);
        console.log(Config.port);
    }
}

그러나 컴파일 단계에서는 수동으로 JSON 파일을 dist 폴더에 복사해야 합니다.요.package.json★★★★

{
    "name"   : "some project",
    "scripts": {
        "build": "rm -rf dist && tsc && cp src/config.json dist/"
    }
}

제 경우 tsconfig.node.json을 변경해야 했습니다.

{
  "compilerOptions": {
    ...
    "resolveJsonModule": true
  },
  "include": [..., "colors.json"]
}

그런 식으로 Import를 하려면:

import * as colors from './colors.json'

또는 다음과 같은 경우:

import colors from './colors.json'

esModule을 사용하여인터op": 참

추가하셔야 합니다.

"resolveJsonModule": true

tsconfig.json 옵션입니다.

Node.js 응용 프로그램에는 .json이 필요한 경우가 많습니다.TypeScript 2.9에서는 --resolveJsonModule을 사용하여 .json 파일을 Import, 추출 및 생성할 수 있습니다.

예#

// tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}

// .ts

import settings from "./settings.json";

settings.debug === true;  // OK
settings.dry === 2;  // Error: Operator '===' cannot be applied boolean and number


// settings.json

{
    "repo": "TypeScript",
    "dry": false,
    "debug": false
}
by: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

또 다른 방법

const data: {[key: string]: any} = require('./data.json');

이것은 와일드카드를 사용할 필요가 없고 원하는 json 유형을 정의할 수 있다는 것입니다.

예를 들어 사용자 지정 유형 json을 입력합니다.

interface User {
  firstName: string;
  lastName: string;
  birthday: Date;
}
const user: User = require('./user.json');

에서 Angular(타자기본)를 ..json 안에 파일링하다environment.ts그러기 위해서는 tsconfig에서 다음 두 가지 옵션을 설정해야 합니다.

{
  "compilerOptions": {
    "moduleResolution": "node",
    "resolveJsonModule": true
  }
}

다음 파일을 수 .environment.ts:

import { default as someObjectName } from "../some-json-file.json";

JSON을 Import한다고 명시적으로 알려주는 tsconfig를 변경하지 않고 JSON 파일을 Import할 수 있습니다.

import mydata  from './mydataonfile.json' assert { type: "json" };

이것이 질문에 완전히 답하지 못한다는 것을 알지만, 많은 사람들이 JSON을 파일에서 직접 로드하는 방법을 알고 싶어 이곳에 옵니다.

능능 enable enable enable enable를 유효하게 "resolveJsonModule": truetsconfig.json이치이 기능은 저에게 도움이 됩니다.

const config = require('./config.json');

주의: @kentor ways 를 사용하는 경우

tsconfig.json (문서)의 컴파일러 옵션 섹션에서 다음 설정을 추가해 주세요.

때 더해야 요.--resolveJsonModule...--esModuleInterop의 배후에tscTypeScript를 사용합니다.

::tsc --resolveJsonModule --esModuleInterop main.ts

요."include": ["src"]로로 합니다."include": ["."]에에 to in "resolveJsonModule":truemanifest.json의 자세가 본연의 ./src

언급URL : https://stackoverflow.com/questions/49996456/importing-json-file-in-typescript

반응형