Typescript path mapping for React Native *.android.ts and *.ios.ts modules Typescript path mapping for React Native *.android.ts and *.ios.ts modules reactjs reactjs

Typescript path mapping for React Native *.android.ts and *.ios.ts modules


Looks like you're running into the issue reported here: https://github.com/Microsoft/TypeScript/issues/8328

According to the issue (and what I've found in my own projects) path resolution doesn't work for relative paths, like what you're doing in your code above. You also don't get type-checking between your .android and .ios files, so I've been using the other approach discussed in the issue:

./ApplicationTabs.d.ts

// This file exists for two purposes:// 1. Ensure that both ios and android files present identical types to importers.// 2. Allow consumers to import the module as if typescript understood react-native suffixes.import DefaultIos from './ApplicationTabs.ios';import * as ios from './ApplicationTabs.ios';import DefaultAndroid from './ApplicationTabs.android';import * as android from './ApplicationTabs.android';declare var _test: typeof ios;declare var _test: typeof android;declare var _testDefault: typeof DefaultIos;declare var _testDefault: typeof DefaultAndroid;export * from './ApplicationTabs.ios';export default DefaultIos;


Continuing the issue… I was working on the same problem, and the simple solution for me is to use:

import ApplicationTabs from './ApplicationTabs/index';

In tsconfig, you don't need any "paths" section.

  1. This makes the tscompiler find the module ./ApplicationTabs/index.ts (this file must exist).Because (from https://github.com/Microsoft/TypeScript-Handbook/blob/release-2.0/pages/Module%20Resolution.md#path-mapping):A relative import will be resolved relative to the importing file. So import { b } from "./moduleB" in source file /root/src/folder/A.ts would result in the following lookups:

    /root/src/folder/moduleB.ts/root/src/folder/moduleB.d.ts
  2. The react-native packager (Metro) will find ./ApplicationTabs``/index.android.ts or ./ApplicationTabs/index.ios.ts, because react-native works that way.


Recommendations here is to use path mapping support, see https://github.com/Microsoft/TypeScript-Handbook/blob/release-2.0/pages/Module%20Resolution.md#path-mapping

so your tsconfig.json should contain something like:

{    "compilerOptions": {        "paths": {            "*": ["*", "*.ios", "*.android"]        }   }}

this will tell the compiler when resolving an import to BigButton to look at:

BigButton.tsx

BigButton.ios.tsx

BigButton.androdid.tsx