我想在反应本机项目中使用节点js作为后端。
答案 0 :(得分:4)
是的,你可以使用ReactNativify作为Big Rich正确陈述的使用为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'
Note2 或者按照此评论中的说明选择.babelrc
解决方案(可能最干净):https://github.com/philikon/ReactNativify/issues/4#issuecomment-312136794
3)我发现我的项目根目录中仍然需要一个.babelrc
来让我的Jest测试工作。有关详细信息,请参阅此问题:https://github.com/philikon/ReactNativify/issues/8
答案 1 :(得分:3)
ReactNativify Github项目确实/做了*,将NodeJS运行时添加到React-Native(RN)项目中。
*目前为not working in RN v0.43.3 onwards, April 2017。
另见(截至2018年5月):