我们可以在反应原生应用程序中使用nodejs代码吗?

我想在本地项目中使用节点js作为后端。

是的,您可以使用ReactNativify作为Big Rich正确的状态来使用为Node编写的软件包。 有些事情要考虑,但:

1)我遵循了我在问题列表中find的build议, transformer.js两个部分拆分为transformer.js

transformers.js(在/config ,从rn-cli.config.js调用):

 const babelTransformer = require('./babel-transformer'); module.exports.transform = function(src, filename, options) { const extension = String(filename.slice(filename.lastIndexOf('.'))); let result; try { result = babelTransformer(src, filename); } catch (e) { throw new Error(e); return; } return { ast: result.ast, code: result.code, map: result.map, filename }; }; 

babel-transformer.js(也在/config ):

 'use strict' const babel = require('babel-core'); /** * This is your `.babelrc` equivalent. */ const babelRC = { presets: ['react-native'], plugins: [ // The following plugin will rewrite imports. Reimplementations of node // libraries such as `assert`, `buffer`, etc. will be picked up // automatically by the React Native packager. All other built-in node // libraries get rewritten to their browserify counterpart. [require('babel-plugin-rewrite-require'), { aliases: { constants: 'constants-browserify', crypto: 'react-native-crypto', dns: 'mock/dns', domain: 'domain-browser', fs: 'mock/empty', http: 'stream-http', https: 'https-browserify', net: 'mock/net', os: 'os-browserify/browser', path: 'path-browserify', pbkdf2: 'react-native-pbkdf2-shim', process: 'process/browser', querystring: 'querystring-es3', stream: 'stream-browserify', _stream_duplex: 'readable-stream/duplex', _stream_passthrough: 'readable-stream/passthrough', _stream_readable: 'readable-stream/readable', _stream_transform: 'readable-stream/transform', _stream_writable: 'readable-stream/writable', sys: 'util', timers: 'timers-browserify', tls: 'mock/tls', tty: 'tty-browserify', vm: 'vm-browserify', zlib: 'browserify-zlib' }, throwForNonStringLiteral: true }], // Instead of the above you could also do the rewriting like this: ["module-resolver", { "alias": { "mock": "./config/mock", "sodium-universal": "libsodium" } }] ] }; module.exports = (src, filename) => { const babelConfig = Object.assign({}, babelRC, { filename, sourceFileName: filename }); const result = babel.transform(src, babelConfig); return { ast: result.ast, code: result.code, map: result.map, filename }; } 

2)正如你在上面的代码中看到的,我也演示了使用babel-plugin-module-resolver

请注意 ,我将使用此插件而不是一个ReactNative使用。 它允许你引用本地文件,并用适当的引号写入允许不符合JS的名称,如“钠通用”

注2或者去看.babelrc解决scheme(也许干净)在这个评论中概述: https : //github.com/philikon/ReactNativify/issues/4#issuecomment-312136794

3)我发现我仍然需要在我的项目的根.babelrc使我的Jesttesting工作。 请参阅此问题的详细信息: https : //github.com/philikon/ReactNativify/issues/8

ReactNativify Github项目只是这样做的,将一个NodeJS运行时添加到React-Native(RN)项目中。

*目前在2017年4月的RN v0.43.3及以后版本中不能使用 。