在create-react-app +打字稿中导入静态JSON [英] Importing static JSON in create-react-app + typescript

查看:125
本文介绍了在create-react-app +打字稿中导入静态JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习打字稿,当前正在尝试导入简单的json文件,该文件在本地存储在由create-react-app引导的项目中.

I am learning typescript and currently trying to import simple json file which I store locally in the project bootstrapped with create-react-app.

data.json看起来像这样:

{
  "test": "123",
}

在我的App.tsx中,我试图使用json-loader导入它. App.tsxdata.json都在同一个文件夹中,导入看起来像这样:

In my App.tsx I am trying to import it using json-loader. Both App.tsx and data.json are in the same folder and the import looks like this:

import data from './data.json'

我已经尝试过解决该问题的几种方法,但是似乎没有任何效果.这些解决方案是import * as data from './data.json'const data = require('./data.json')

I've already tried couple solutions to this problem but nothing seems to work. Those solutions are import * as data from './data.json' and const data = require('./data.json')

推荐答案

解决方案1:您可以使用以下语句创建一个名为data.json.ts的新文件:

Solution 1: You can create a new file named data.json.ts with this statement:

export default {your_json};

然后导入:

import { default as data } from './path/data.json';

ref: https://github.com/frankwallis/plugin-typescript/issues /129

解决方案2:这里的问题是,当您编译项目(例如,将其编译到名为lib的文件夹中)时,您的lib文件夹中没有.json文件.您可以简单地将该文件包含在您的构建中,或手动将该文件复制到您的lib文件夹中. 要导入文件,您必须使用:

Solution 2: The problem here that when you compile your project (for example into a folder named lib) you don't have your .json file inside your lib folder. You simple can include that file into your build or manually copy that file into your lib folder. To import your file you have to use:

  • const data = require('data.json');
  • 声明您自己的类型. 创建一个名为 your_file_name.d.ts 的新文件,并将以下代码粘贴到该文件中:
  • const data = require('data.json');
  • declare your own type. Create a new file named your_file_name.d.ts and stick into this file the following code:
declare module "*.json" 
{
    const value: any;
    export default value;
}

这篇关于在create-react-app +打字稿中导入静态JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆