Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common js modules in react native

Is it possible to make use of common js modules with react-native? The use case is sharing logic between a mobile and web version of a react project.

like image 211
westymatt Avatar asked Mar 31 '15 16:03

westymatt


People also ask

What is common JS module?

From a structure perspective, a CommonJS module is a reusable piece of JavaScript that exports specific objects made available to any dependent code. Unlike AMD, there are typically no function wrappers around such modules (so we won't see define here, for example).

What are native modules in React Native?

What's a Native Module? A native module is a set of javascript functions that are implemented natively for each platform (in our case is iOS and Android). It is used in cases where native capabilities are needed, that react native doesn't have a corresponding module yet, or when the native performance is better.

What is JavaScript used in React Native?

In most cases, React Native will use JavaScriptCore, the JavaScript engine that powers Safari. Note that on iOS, JavaScriptCore does not use JIT due to the absence of writable executable memory in iOS apps.

Can I use any JS library in React Native?

​ Usually libraries built specifically for other platforms will not work with React Native. Examples include react-select which is built for the web and specifically targets react-dom , and rimraf which is built for Node. js and interacts with your computer file system.


1 Answers

Ok, I'm new to this too but I think I've figured out how to include js code. I didn't have to add anything to the standard react native installation.

Create a Library of code:

//library.js
exports.foo = function() {

  //Do stuff here
  return "Here";

}

Import into another js file:

var lib = require("./library.js");
var myString = lib.foo();

I found the info from this blog post:

http://0fps.net/2013/01/22/commonjs-why-and-how/

like image 115
Daniel Avatar answered Sep 22 '22 10:09

Daniel