【发布时间】:2019-02-18 13:57:03
【问题描述】:
我正在学习打字稿,目前正在尝试导入简单的 json 文件,该文件我存储在本地通过 create-react-app 引导的项目中。
data.json 看起来像这样:
{
"test": "123",
}
在我的App.tsx 中,我尝试使用json-loader 导入它。 App.tsx 和 data.json 都在同一个文件夹中,导入如下所示:
import data from './data.json'
我已经尝试了几个解决这个问题的方法,但似乎没有任何效果。这些解决方案是import * as data from './data.json' 和const data = require('./data.json')
【问题讨论】:
-
您遇到什么错误?您是否弹出了
create-react-app配置?您可能需要共享您添加json-loader的 webpack 配置部分。你的 import 语句看起来不错 StackBlitz -
var data = require('./data.json');试试这个 -
@AlexanderStaroselsky 我没有弹出,假设 json-loader 嵌入在 react-scripts 中。根据我尝试做的事情,我得到不同的错误:在这种情况下
import * as data from './data.json'我可以控制台记录数据但错误是...containers/App.tsx(3,23): Cannot find module './data.json'。 -
我假设您在使用 TypeScript 时被弹出。您如何在
create-react-app项目中将 TypeScript 与 Webpack 集成?您可能应该分享您的配置,以便其他人可以帮助回答您的问题。 -
@AlexanderStaroselsky 我想没什么可分享的,我刚刚运行了
create-react-app my-app --scripts-version=react-scripts-ts当我尝试像您在沙箱中所做的那样导入时,它给了我Cannot find module'./data.json' 错误.
标签: javascript json reactjs typescript