问题描述
考虑一个场景,我们用release
模式构建我们的react-native
应用,同时具有如下代码:
Consider having a scenario, where we build our react-native
App with release
mode while having code like below:
let img;
if ( __DEV__ ) {
img = require('./debug-image.png');
} else {
img = require('./real-image.png');
}
我的问题是,debug-image.png
和real-image.png
是否都将捆绑到APK
中(即使debug-image.png
从未在其他任何地方使用),或者捆绑器是否检测到debug-image.png
文件未使用(并且不将其包含在捆绑包中)?
My question is, will both debug-image.png
and real-image.png
get bundled into the APK
(even though the debug-image.png
is never used anywhere else), or does the bundler detect that the debug-image.png
file is not used (and does NOT include it into the bundle)?
推荐答案
手动测试:
我们可以通过构建未签名的发行版APK
来简单地对其进行测试(如),一次,其代码如下(第一种情况):
Manual Testing:
We can simply test it out ourselves, by building an unsigned-release APK
(as mentioned in another post), two times, once with codes like below (the First-Case):
let bigFile;
if ( __DEV__ ) {
bigFile = require('./big-file.dat');
} else {
bigFile = require('./small-file.dat');
}
在上面,将!
添加到if语句中,例如if ( ! __DEV__ ) { ...
,导致APK
-size增加了50 mb
(即./big-file.dat
的大小).
In above, adding !
to the if-statement, like if ( ! __DEV__ ) { ...
, caused the APK
-size to increase by 50 mb
(i.e. the size of ./big-file.dat
).
再一次,使用下面的代码(第二种情况)进行了测试:
And another time, tested with codes like below (the Second-Case):
let bigFile = require('./big-file.dat');
if ( ! __DEV__ ) {
bigFile = null;
}
无论我做什么,APK
-size都保持很大.
where no matter what I did the APK
-size did just keep huge.
根据APK
-size的变化,我确定并且可以告诉您(在撰写本文时,是2019
):
According to the APK
-size change, I am sure and can tell that (in the time of writing, namely 2019
):
- 捆绑器足够智能,可以处理第一案,并从捆绑中排除仅在非活动if语句内部使用的文件.
- 但是另一方面,它无法优化文件,该文件曾在稍微复杂一点的Second-Case中使用(它根本无法跟踪变量).
考虑到以上内容,并且捆绑程序足够智能,在某些情况下甚至可以将文件从捆绑中排除,换句话说,我们可以安全地使用常量__DEV__
,而react-native
框架为我们提供了常量.
Considering above and that the bundler is intelligent enough, and can in some cases even exclude files from the bundle, under other means that we can safely use the constant __DEV__
, which react-native
framework provides us.
这篇关于react-native捆绑程序可以检测未使用的文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!