developer tip

TypeScript에서 json 파일 가져 오기

copycodes 2020. 9. 20. 10:05
반응형

TypeScript에서 json 파일 가져 오기


나는이 JSON모양이 다음과 같이 해당 파일을 :

{

  "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"
}

.tsx파일 로 가져 오려고 합니다. 이를 위해 유형 정의에 다음을 추가했습니다.

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

그리고 저는 이것을 이렇게 가져옵니다.

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

그리고 파일에서 색상 primaryMaincolors.primaryMain. 그러나 오류가 발생합니다.Property 'primaryMain' does not exist on type 'typeof "*.json"

내가 뭘 잘못하고 있죠?


가져 오기 양식과 모듈 선언은 모듈의 모양, 내보낼 내용에 대해 동의해야합니다.

쓸 때 (호환되는 모듈 형식을 대상으로 할 때 TypeScript 2.9 이후 JSON 파일에 대한 나쁜 습관 은 note 참조 )

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

로 끝나는 지정자가있는 모든 모듈에는 유형이 지정된 .json단일 내보내기 default가 있음을 나타 any냅니다.

이러한 모듈을 사용할 수있는 방법에는 여러 가지가 있습니다.

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

The first form is the best and the syntactic sugar it leverages is the very reason JavaScript has default exports.

However I mentioned the other forms to give you a hint about what's going wrong. Pay special attention to the last one. require gives you an object representing the module itself and not its exported bindings.

So why the error? Because you wrote

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

And yet there is no export named primaryMain declared by your "*.json".

All of this assumes that your module loader is providing the JSON as the default export as suggested by your original declaration.

Note: Since TypeScript 2.9, you can use the --resolveJsonModule compiler flag to have TypeScript analyze imported .json files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. This is not supported for certain target module formats.


With TypeScript 2.9.+ you can simply import JSON files with typesafety and intellisense like this:

import colorsJson from '../colors.json';
console.log(colorsJson.primaryBright);

Make sure to add these settings in the compilerOptions section of your tsconfig.json (documentation):

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

Side notes:

  • Typescript 2.9.0 has a bug with this JSON feature, I believe it got fixed with 2.9.1 or 2.9.2
  • The esModuleInterop is only necessary for the default import of the colorsJson. If you leave it set to false then you have to import it with import * as colorsJson from '../colors.json'

It's easy to use typescript version 2.9+. So you can easily import JSON files as @kentor decribed.

But if you need to use older versions:

You can access JSON files in more TypeScript way. First, make sure your new typings.d.ts location is the same as with the include property in your tsconfig.json file.

If you don't have an include property in your tsconfig.json file. Then your folder structure should be like that:

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

But if you have an include property in your tsconfig.json:

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

Then your typings.d.ts should be in the src directory as described in include property

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

As In many of the response, You can define a global declaration for all your JSON files.

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

but I prefer a more typed version of this. For instance, let's say you have configuration file config.json like that:

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

Then we can declare a specific type for it:

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

It's easy to import in your typescript files:

import * as Config from 'config.json';

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

But in compilation phase, you should copy JSON files to your dist folder manually. I just add a script property to my package.json configuration:

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

In your TS Definition file, e.g. typings.d.ts`, you can add this line:

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

Then add this in your typescript(.ts) file:-

import * as data from './colors.json';
const word = (<any>data).name;

Another way to go

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

This was you still can define json type is you want and don't have to use wildcard.

For example, custom type json.

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

참고URL : https://stackoverflow.com/questions/49996456/importing-json-file-in-typescript

반응형