是的,您可以通过使用 ReactNativify 来使用为 Node 编写的包,正如 Big Rich 正确声明的那样。
不过需要考虑的一些事项:
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