Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import JS library to typescript in React Native project

How can I import js library (in my case xhook library) into my react native project written in typescript? Or How can I create typescript header file for external js library?

like image 532
JaSHin Avatar asked May 03 '18 08:05

JaSHin


People also ask

Can I use JS library in TypeScript?

The short answer is definitely YES ! but you need some intermediate steps! Please note that you can write plain old JavaScript in a TypeScript project without any problems since JavaScript is a subset of TypeScript, you only need these steps if you are planning to use an external JavaScript library with TypeScript.

How do you use react JS library in react native?

React Native does not and cannot use this library, because you don't have DOM underneath a react native application. However you can use most of the code/functionality you wrote for your mobile app in the browser, if you install necessary transpiling library.

Can I use JavaScript libraries in react native?

Based on the awesome React library (that we already use), React Native lets you develop applications for Android and iOS using Javascript, hopefully making the development process easier and more consistent.


3 Answers

You can simply use:

const signalrLib = require("react-native-signalr").default
like image 176
JaSHin Avatar answered Oct 18 '22 18:10

JaSHin


TypeScript compiles to plain Javascript just like Babel or any other extended Javascript language.

So when you add example xhook to your project, project owner has already compiled his/her TypeScript code into plain JS and you import it just like any other library.

eg. import xhook from 'xhook' or so on how library author has specified.

You can see it yourself if you visit xhook's git page https://github.com/jpillora/xhook you can see compiled code in folder dist and in package.json -file, attribute main points to that file.

TypeScript is not itself language that is runned in browser, but that it is always compiled to plain JavaScript. Hopefully this helps out making a grasp how this works.

edit. seems like xhookis actually written in CoffeeScript but this same rule applies to it as well.

like image 21
Jimi Pajala Avatar answered Oct 18 '22 17:10

Jimi Pajala


As suggested, You can use any ES6/ES2015 notation in typescript. With the new typescript, import will be

import xhook from 'xhook';

Older version:

import * as xhook from 'xhook'

Some module doesnt have type support. You can look for type support as

yarn add @types/xhook

If you dont find type support you can use, node require syntax

const xhook = require('xhook');

For that you may have to declare, require definition like:

declare const require: any;
like image 25
xdeepakv Avatar answered Oct 18 '22 17:10

xdeepakv