简体   繁体   中英

Babel,Webpack,ES6,React: Importing module then passing imported module as prop to child

If I were to import the lodash util library (or any library) in a parent component, and then pass that imported variable as a prop to a child component that I know will use that same library, does this provide any benefits in terms of performance or build time, etc?

I don't imagine I would have to have an import statement for the lodash util library in the child component because it exists as a prop but are there any other benefits in terms of performance?

Is this a common pattern in writing react components or is it something that can be done but not necessarily should be done?

If you are using Webpack there is no performance increase, it brings everything into the same file (or multiple files if you are making multiple chunks) anyway and optimizes the dependency inclusion so you don't have to do it yourself. If anything what you are saying will probably have worse performance because you will add the entire library as a prop to a child component.

Passing a dependency as a prop is basically dependency injection. There will be all pros and cons that are inherent to DI.

One of possible DI benefits is testability. In React ecosystem it is commonly addressed for ES modules alone with Jest module mocking.

Another benefit is extensibility. This works best with DI containers. DI containers in React are explained in this article or this one that uses Angular DI .

For a library like Lodash that isn't expected to be swapped this can be considered an antipattern. ES modules are supposed to serve this purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM