React-native升级记录(3):__DEV__追根溯源

本文深入探讨了React Native中调试模式的实现原理,详细解析了如何通过__DEV__变量判断当前运行环境,揭示了在不同编译方式下__DEV__变量的真值表现及其背后的原因。对于希望深入了解React Native内部机制的开发者来说,是一篇不可多得的技术文章。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

          React-native开发中用来判断当前debug/release环境的方法,rn提供的官方方案中通过__DEV__来判断是一种。一次编译中发现直接使用./gradlew assembleDebug 并不会使用debug环境的配置,原因就是__DEV__是false的。而用react-native run-android编译的时候__DEV__才是true的。why?

          这就要找到__DEV__的出处,从源头找起,react-native是一个命令,在node_module/react_native里面实现,去里面找实现的代码。node_modules/metro 中可以找到

 22 function getPreludeCode(_ref) {
 23   let extraVars = _ref.extraVars,
 24     isDev = _ref.isDev;
 25   const vars = [].concat(_toConsumableArray(formatExtraVars(extraVars)), [
 26     `__DEV__=${String(isDev)}`,
 27     "__BUNDLE_START_TIME__=this.nativePerformanceNow?nativePerformanceNow():Date.now()",
 28     "process=this.process||{}"
 29   ]);
 30
 31   return `var ${vars.join(",")};${processEnv(
 32     isDev ? "development" : "production"
 33   )}`;
 34 }

疑似设置到了环境变量。发现是bundle的时候设置的。bundle的调用在:node_modules/react-native/react.gradle

 52             // Set up dev mode
 53             def devEnabled = !(config."devDisabledIn${targetName}"
 54                 || targetName.toLowerCase().contains("release"))

 55
 56             def extraArgs = extraPackagerArgs;
 57             println "louyong add for test:" + devEnabled;
 58             println "louyong add for test:" + targetName;
 59             if (bundleConfig) {
 60                 extraArgs = extraArgs.clone()
 61                 extraArgs.add("--config");
 62                 extraArgs.add(bundleConfig);
 63             }
 64
 65             if (Os.isFamily(Os.FAMILY_WINDOWS)) {
 66                 commandLine("cmd", "/c", *nodeExecutableAndArgs, cliPath, bundleCommand, "--platform", "android", "--dev", "${devEnabled}",
 67                     "--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir, *extraArgs)
 68             } else {
 69                 commandLine(*nodeExecutableAndArgs, cliPath, bundleCommand, "--platform", "android", "--dev", "${devEnabled}",
 70                     "--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir, *extraArgs)
 71             }

所以要使得__DEV__为true,必须要满足这个红色的if才行。初步调研结论,仅供参考:)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值