Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 2.0 with React Native

I'm just getting started with Typescript and I'm attempting to use it with a new React Native project. However, I can get TS to compile. I've based my setup off of this article with the exception of using npm @types. I get the correct type hinting in my IDE (Atom), but when I attempt to compile, I get the following error:

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'.
...

My 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"
  }
}

My 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"
  ]
}
like image 239
csm232s Avatar asked Nov 19 '25 08:11

csm232s


1 Answers

Since you are using "typescript": "^2.0.3", the error is caused by this reported issue. There is work around for this, which is using "moduleResolution": "node". Be aware that it will not make classic module resolution works for packages afterwards.

@Leone: your fix "module": "commonjs" will not work since React Native ships with ES2015, require() modules will cause run time errors in React Native.

like image 152
br1anchen Avatar answered Nov 21 '25 22:11

br1anchen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!