【问题标题】:Tell React Native to use App.tsx instead of App.js告诉 React Native 使用 App.tsx 而不是 App.js
【发布时间】:2018-12-21 11:35:00
【问题描述】:

我已经使用 TypeScript 搭建了一个项目,但我的主要 index.js 文件引用了 App.js 而不是 App.tsx

如何设置我的项目以便使用 TypeScript 文件 (App.tsx) 而不是 App.js?

这是我的项目结构:

这是通过react-native init X --template typescript搭建的

【问题讨论】:

  • TS 是一种编译成 JS 的语言。这就是为什么您需要将 .tsx 文件编译为 .js 并将初始索引文件指向已编译文件的原因。
  • @zvona 如何在我的 App.tsx 中编写代码并让它自动编译为 App.js?目前,我有 App.js 和 App.tsx。
  • 我感觉你已经这样做了,但只是为了谨慎起见:例如你有 inputFolder /src/App.tsx 和 outputFolder 的结构/dist/App.jsindex.js 将指向 ./dist/App.js。然后你运行 TypeScript watcher (tsc --watch),它会在你每次进行更改时编译 tsx。 TS 行为在 tsconfig.json 中配置。

标签: typescript react-native


【解决方案1】:

您能添加您的相关文件夹结构吗?

我建议您创建一个包含所有 .ts(x) 文件的单独源文件夹,包括 App.tsx 甚至 index.ts 您将所有这些文件编译到构建文件夹中,这意味着您的 index.js 也将在里面该文件夹不再位于您的项目根目录中。

然后你只需调整 android 和 ios 文件夹中的 build.gradle 和 AppDelegate.m 以引用 build/index.js 而不是 index.js。并且不要忘记更新任何引用 index.js 的 package.json 脚本(如构建脚本)。

我认为将所有 JS 与 TS 严格分开会更有意义。

【讨论】:

  • 好的,谢谢!就像我提到的:我认为最好将 App.tsx 模式设置为 src 文件夹,然后在 index.js 文件中引用编译后的版本。
猜你喜欢
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 2023-03-18
  • 2012-10-27
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
相关资源
最近更新 更多