首页 > 解决方案 > 如何使用 Yarn 和 Typescript 设置 React-Native

问题描述

所以到目前为止,我一直在使用准系统 react-native 和 npm 来处理我的项目,并且一切正常,但现在我遇到了一个问题

我需要在后期添加一个新功能,这会让人头疼,因此我决定重新开始构建,因为我可以修复许多错误的编码和错误。

现在这将是一个不同的设置,我不打算使用 npm,我想使用 yarn。我不打算单独使用 React-Native,我打算将它与 typescript 一起使用!

现在这是我使用安装程序在 Windows 笔记本电脑上安装纱线的问题,但我不完全确定如何创建 react-native 应用程序并在此基础上添加打字稿。浏览文档和其他论坛,关于如何创建 react-native 应用程序或如何使用它设置 typescript 的答案不断变化。所以请告诉我

如何在 Windows 笔记本电脑上使用带有 typescript 的 yarn 设置 react-native 应用程序?

标签: javascripttypescriptreact-nativeyarnpkgcreate-react-native-app

解决方案


这对我有用:

创建你的 react-native 应用程序:

npx react-native init MyApp
cd MyApp

添加打字稿:

yarn add -D typescript @types/jest @types/react @types/react-native @types/react-test-renderer

然后创建一个tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

还有一个jest.config.js

module.exports = {
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};

将您的更改App.jsApp.tsx.

这就对了。type现在,您可以根据需要使用更严格的规则更改配置文件。

所有文档都在https://reactnative.dev/docs/typescript中。

旁注: npx react-native init MyApp --template react-native-template-typescript 在构建应用程序时导致错误。 这就是我尝试使用上述方法的原因。


推荐阅读