我们可以在React Native应用程序中使用Node.js代码吗?
我想将node js用作react native项目中的后端。
回答:
是的,您 可以 通过正确使用Big Rich的ReactNativify 来 使用为Node编写的包。但是要考虑一些事项:
1)我遵循在问题清单中找到的建议,并分为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兼容名称,例如“
sodium-universal”
或.babelrc
按此评论所述寻求解决方案(可能是最干净的):https
:
//github.com/philikon/ReactNativify/issues/4#issuecomment-312136794
3)我发现我仍然需要.babelrc
在项目的根目录中使用a
才能使Jest测试正常工作。有关详细信息,请参见此问题:https
:
//github.com/philikon/ReactNativify/issues/8
以上是 我们可以在React Native应用程序中使用Node.js代码吗? 的全部内容, 来源链接: utcz.com/qa/418925.html