react-native bundler 可以检测未使用的文件吗? [英] Can react-native bundler detect unused files?
问题描述
考虑一个场景,我们使用 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
-大小增加50 MB
(即./big-file.dat
的大小).
Which in, adding !
to above 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
大小都保持巨大.
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
):
- 打包器足够智能,可以处理 First-Case 并从包中排除仅在非活动 if 语句中使用的文件.
- 但另一方面,它无法优化文件,该文件用于稍微复杂的 Second-Case(它只是不跟踪变量).
考虑到打包器足够智能,在某些情况下甚至可以从包中排除文件,在其他情况下,我们可以安全地使用常量__DEV__
(react-native
框架为我们提供).
Considering 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
与 type-script 模板一起使用,例如 "react-native init MyApp --template typescript
",但我希望这对于在非打字稿模板中使用的打包器也是如此!!
Note: I am using
react-native
with the type-script template, like "react-native init MyApp --template typescript
", but I hope this is even true for the bundler which is used in none-typescript template as well !!
这篇关于react-native bundler 可以检测未使用的文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!