我想将node js用作react native项目中的后端。
是的,您 可以 通过正确使用Big Rich的ReactNativify 来 使用为Node编写的包。但是要考虑一些事项:
1)我遵循在问题清单中找到的建议,并分为transformer.js两部分:
transformer.js
Transformers.js(在/config和中调用rn-cli.config.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。
babel-plugin-module-resolver
注意 ,我将使用该插件而不是ReactNative所使用的插件。它允许您引用本地文件,并用适当的引号书写允许使用非JS兼容名称,例如“ sodium-universal”
注意2 或.babelrc按此评论所述寻求解决方案(可能是最干净的):https : //github.com/philikon/ReactNativify/issues/4#issuecomment-312136794
.babelrc
3)我发现我仍然需要.babelrc在项目的根目录中使用a 才能使Jest测试正常工作。有关详细信息,请参见此问题:https : //github.com/philikon/ReactNativify/issues/8