且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 React Native 项目中使用 npm 模块

更新时间:2023-12-03 18:02:58

好吧,恰恰相反.React Native 实际上在 io.js 运行时内运行,因此大多数用于 node 的纯 JavaScript 模块都可以工作.另一方面,大多数为 React.js 编写的前端模块不适用于 React-Native.

React Native 不使用我们从网络上知道的 HTML DOM 或 CSS.它用原生视图表示替换了 CSS/HTML DOM.因此,任何应该使用 HTML 并在浏览器中显示的前端包都将不起作用.

另一方面,任何在 node.js/io.js 中运行的纯 javascript 模块都可以在 react-native 中运行.

例如,我非常确定 Facebook 在他们的 react-native 应用程序中使用了他们的中继"数据访问库(这是一个 javascript 库,可以通过 Facebook 的 Open Graph API 有效地进行通信并允许访问 Facebook 用户的数据).>

这样做的方法与其他 node.js/io.js 应用程序中的相同.只需运行

npm install module --save

大功告成(package.json 将自动更新模块的依赖项).然后你就可以照常使用这个包了.

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.

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.