6

I recently saw a suggestion about deep requiring in a module -

Note: If you don't want the ReactART based components and it's dependencies, do a deep require instead: import ProgressBar from 'react-native-progress/Bar';.

Based on my knowledge - without adding/configuring Webpack 2 with tree-shaking and enabling uglify by oneself - the RN bundler would not be tree shaking and removing unused modules.

Given that, would deep requiring as suggested really lead to unused dependencies not being included in the final bundle?

Derrick Beining
  • 876
  • 8
  • 15
prithsharma
  • 111
  • 6
  • I'd recommend updating the question title to: "Does react-native's bundler optimize with tree shaking?" or something to that effect – Derrick Beining Apr 04 '18 at 17:00

1 Answers1

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.

Robert Fischer
  • 1,436
  • 12
  • 26