有没有办法通过 JavaScript 代码动态获取带有端口或完整路径的 React Native 打包器 ip -
jsCodeLocation
?它可以是 localhost:8081
或 192.168.0.1.xip.io:8081
。这取决于运行设备 - 模拟器还是真实设备
我在ReactNative源代码中找到了NativeModules并在这里发现了scriptURL:
import { NativeModules } from 'react-native';
...
const scriptURL = NativeModules.SourceCode.scriptURL;
const address = scriptURL.split('://')[1].split('/')[0];
const hostname = address.split(':')[0];
const port = address.split(':')[1];
它适用于模拟器和设备!
import { NativeModules } from 'react-native';
import url from 'url';
const { hostname } = url.parse(NativeModules.SourceCode.scriptURL);
2024 0.73 更新版本 - TurboModules - 启用新架构
const SourceCode = TurboModuleRegistry.getEnforcing("SourceCode");
const scriptURL = SourceCode.getConstants().scriptURL;
const address = scriptURL.split('://')[1].split('/')[0];
const hostname = address.split(':')[0];
const port = address.split(':')[1];