react-native捆绑程序可以检测未使用的文件吗? [英] Can react-native bundler detect unused files?

查看:53
本文介绍了react-native捆绑程序可以检测未使用的文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个场景,我们用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.pngreal-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与类型脚本模板一起使用,例如"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捆绑程序可以检测未使用的文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆