dashman
dashman

Reputation: 3018

Nativescript - platform specific code

I've got an iOS specific code (class definition) and would like to include in a separate ios specific file.

So I created two files

utils2.ios.ts <-- added my code here

utils2.android.ts

And then from another file, I did:

import utils2 = require("./utils2");

But I'm getting an error message that the module is not found.

I had to go this route because I've got a class definition in the code and if I have just one file, I get a run-time error on Android.

Does typescript support platform specific files?

Or another option - is something like this possible in ts file

if ios

do this

end

Similar to C preprocesser

Upvotes: 1

Views: 1658

Answers (1)

Brad Martin
Brad Martin

Reputation: 6177

You can get by with just a utils.ts file and inside it you can do platform specific logic that you mention. Your issue about the module not found is likely just a path issue to that module, not that the module isn't actually there. Also note that Typescript doesn't really "support" platform specific files. Nativescript takes those .android.ts and .ios.ts files and at runtime loads the file you need on the platform running. So just FYI that's not really TS related :)

Nativescript provides a platform module in the tns-core-modules. Import the { isAndroid } or { isIOS } from the platform module in your code and use it as the

if (isAndroid) { 
  // do android only here 
} else { 
  // ios 
}

Upvotes: 3

Related Questions