Using npm modules in React Native projects

2019-01-22 11:29发布

问题:

Is it possible to use npm modules with React Native projects directly, like one uses them within a React project by npm install <module-name>?

Of course I mean modules that can be used with a React app, that is front-end ones that will be run in the browsers JS runtime but not in the nodejs or iojs runtime as a React Native app does not run in the nodejs or iojs runtime.

回答1:

Well, it's quite opposite. React Native actually runs within io.js runtime so most pure javascript modules for node will work. On the other hand most front-end modules written for React.js will not work for React-Native.

React Native does not use HTML DOM nor CSS as we know it from the web. It replaces the CSS/HTML DOM with the native view representation. So any front-end packages that are supposed to use HTML and be displayed in browser will not work.

On the other hand, any modules that are pure javascript and run within node.js/io.js are perfectly OK to be run in react-native.

For example, I am quite sure that Facebook uses their 'relay' data access library in their react-native apps (it's a javascript library that efficiently communicates over Facebook's Open Graph API and allows to access Facebook user's data).

The way to do it is the same as in other node.js/io.js apps. Simply run

npm install module --save

and you are done (package.json will be automatically update with the dependency for the module). Then you can use the package as usual.