将TypeScript添加到React-Native Expo项目

Ben*_*Ben 2 typescript react-native expo

我正在尝试将TypeScript添加到React-Native Expo项目中,如果将任何文件重命名abc.js为,则会出现以下错误abc.tsx

我一直在按照以下说明进行操作:

我该如何解决?


rn-cli.config.js

module.exports = {
  getTransformModulePath() {
    return require.resolve('react-native-typescript-transformer');
  },
  getSourceExts() {
    return ['ts', 'tsx', 'js', 'jsx'];
  }
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
"compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "jsx": "react",
    "outDir": "./dist",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true,
    //"strict": true,
    "skipLibCheck": true,
    "declaration": true,
    "noUnusedLocals": true
},
"exclude": [
    "node_modules"
]
}
Run Code Online (Sandbox Code Playgroud)

EQu*_*per 5

使用版本 31 + typescript 可以更轻松地添加https://docs.expo.io/versions/latest/guides/typescript/

首先安装开发依赖项react-native-typescript-transformer

您需要在您的app.json文件中添加此配置。这将使 expo 知道您使用 ts.

 "packagerOpts": {
      "sourceExts": [
        "ts",
        "tsx"
      ],
      "transformer": "node_modules/react-native-typescript-transformer/index.js"
    },
Run Code Online (Sandbox Code Playgroud)

停止展会并在完成这些更改后重新启动。

如果你使用普通的react-native,rn-cli.config.js文件就是响应,但在博览会上,这就是我让它工作的方式。


tia*_*gob 5

TS / TSX文件在expo v31中开箱即用,但您可能需要包含

包TypeScript类型

yarn add @types/expo @types/react @types/react-native -D

自定义tsconfig.json

tsconfig.json在旁边的根目录中创建package.json。它强制执行严格模式,并包含App.tsx(以替换App.js)和“ custom_types”目录,以为不包含它们的npm软件包添加类型。

// Defaults from https://blogs.msdn.microsoft.com/typescript/2018/08/27/typescript-and-babel-7/
// Added "jsx": "react-native".
// Added ["App.tsx", "custom_types"] to "include".
{
  "compilerOptions": {
    // Target latest version of ECMAScript.
    "target": "esnext",
    // Search under node_modules for non-relative imports.
    "moduleResolution": "node",
    // Output react-native code.
    "jsx": "react-native",
    // Don't emit; allow Babel to transform files.
    "noEmit": true,
    // Enable strictest settings like strictNullChecks & noImplicitAny.
    "strict": true,
    // Disallow features that require cross-file information for emit.
    "isolatedModules": true,
    // Import non-ES modules as default imports.
    "esModuleInterop": true
  },
  "include": ["src", "App.tsx", "custom_types"]
}
Run Code Online (Sandbox Code Playgroud)