6

我最近在一个模块中看到了一个关于深度需求的建议——

注意:如果您不想要基于 ReactART 的组件及其依赖项,请改为执行深层要求:从 'react-native-progress/Bar' 导入 ProgressBar;。

根据我的知识——没有添加/配置 Webpack 2 与 tree-shaking 并自己启用 uglify——RN 捆绑器不会进行 tree-shaking 和删除未使用的模块。

鉴于此,建议的深度需求真的会导致未使用的依赖项不包含在最终捆绑包中吗?

4

1 回答 1

2

The React-Native bundler is called Metro, and (as of this writing) there is an open issue fore tree shaking with a delivery in "H1 2019".

Note that Uglify.js (or anything else that acts solely on a single file) is not capable of doing tree shaking, because tree shaking is (by definition) between modules — the equivalent to tree shaking within a single module is simply called "dead code elimination". So you need to do proper tree shaking at the bundler level.

To answer the final question in the OP: yes, if you do a deep include, you will exclude unused dependencies. When you do an import, you are creating a dependency on a specific JavaScript file (and, transitively, the files it depends on). You are only importing a single JavaScript file, even if you import using the short-hand of merely saying the module name (eg: import "react-native-progress"): in that case, the single file you are creating a dependency on the file named in package.json under the main field (cf: the browser field).

Conventionally, that main file is simply re-exporting (that is, creating a dependency upon and exposing) other modules. That is exactly what index.js does in react-native-progress, which is why you end up importing all the package's modules when you do the generic module import. When you do the so-called "deep require", you're just bypassing the re-exporting that the index.js does, and instead setting up the dependency to the deeper module yourself.

于 2018-12-09T17:58:51.473 回答