简体   繁体   English

Babel,Webpack,ES6,反应:导入模块,然后将导入的模块作为prop传递给子级

[英]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? 如果我要在父组件中导入lodash util库(或任何库),然后将该导入的变量作为道具传递给我知道将使用相同库的子组件,这是否会对性能产生任何好处或建立时间等?

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? 我不认为我必须在子组件中为lodash util库提供一个import语句,因为它作为prop存在,但是在性能方面还有其他好处吗?

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. 如果您使用的是Webpack,则不会提高性能,它会将所有内容带入同一文件(如果要创建多个块,则将多个文件带入)并优化了依赖项包含,因此您不必自己做。 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. DI将具有所有固有的利弊。

One of possible DI benefits is testability. DI可能带来的好处之一就是可测试性。 In React ecosystem it is commonly addressed for ES modules alone with Jest module mocking. 在React生态系统中,通常通过Jest模块模拟单独解决ES模块问题。

Another benefit is extensibility. 另一个好处是可扩展性。 This works best with DI containers. 这最适合DI容器。 DI containers in React are explained in this article or this one that uses Angular DI . 本文本使用Angular DI的 文章将介绍React中的DI容器。

For a library like Lodash that isn't expected to be swapped this can be considered an antipattern. 对于不希望交换的Lodash这样的库,可以将其视为反模式。 ES modules are supposed to serve this purpose. ES模块应达到此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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