Typescript 2.0 with React Native

Typescript 2.0 with React Native

本文关键字:React Native with Typescript      更新时间:2023-09-26

我刚刚开始使用Typescript,我正试图在一个新的React Native项目中使用它。然而,我可以得到TS编译。除了使用npm @types之外,我的设置都是基于这篇文章。我在IDE (Atom)中得到了正确的类型提示,但是当我尝试编译时,得到了以下错误:

node_modules/@types/react-native/index.d.ts(19,24): error TS2307: Cannot find module 'react'.
node_modules/@types/react-native/index.d.ts(222,28): error TS2304: Cannot find name 'Component'.
node_modules/@types/react-native/index.d.ts(1017,15): error TS2304: Cannot find name 'Ref'.
...
我package.json

{
  "name": "healthymeIngage",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "15.3.2",
    "react-native": "0.35.0"
  },
  "jest": {
    "preset": "jest-react-native"
  },
  "devDependencies": {
    "@types/react": "^0.14.41",
    "@types/react-native": "^0.29.36",
    "babel-jest": "16.0.0",
    "babel-preset-react-native": "1.9.0",
    "jest": "16.0.2",
    "jest-react-native": "16.0.0",
    "react-test-renderer": "15.3.2",
    "typescript": "^2.0.3"
  }
}
我tsconfig.json

{
  "compilerOptions": {
    "module": "es2015",
    "target": "es2015",
    "jsx": "react",
    "outDir": "build",
    "rootDir": "src",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "noImplicitAny": true,
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "node_modules/@types/**/*.ts"
  ]
}

因为您使用的是"typescript": "^2.0.3",所以这个错误是由这个报告的问题引起的。有一种方法可以解决这个问题,就是使用"moduleResolution": "node"。请注意,它不会使经典的模块解析对之后的包起作用。

@Leone:你的修复"module": "commonjs"将不工作,因为React Native船与ES2015, require()模块将导致运行时错误在React Native

我将tsconfig.json文件中的模块系统("module": "es2015"行)更改为:

"module": "commonjs",