我试图将我的代码(服务器端和客户端)尽可能保持模块化,这需要大量导入和 出口,但我有一个悬而未决的问题。</ p>

我试图从这里搜索,我阅读了热门的博客文章,甚至看了几个YT视频,但它仍然没有完全解释。 我希望现在避免犯这个错误,避免以后重写我的逻辑。</ p>

File1 </ strong> </ p>
\ n


</ code> </ pre>

File2 </ strong> </ p >


</ code> </ pre>

File3 </ strong> </ p>

 从'./file1'导入File1;从'。/ file2'执行File2; 
nn //对两者执行操作 </ pre>

  • 它足够聪明吗? 我可以根据需要导入相同的
    module,它只导入一次吗?</ li>
  • 如果我需要导入React </ code>到 File3 </ strong>怎么办? 太? 是否仍然足够聪明来处理这种情况? </ li>
    </ ul>

    我正在使用Node,Babel和Webpack。</ p>
    </ div>



Im trying to keep my code (sever and client side) as modular as possible and this requires a lot of importing and exporting, however I have an unanswered question.

I tried to search from here, I read topical blog posts and even watched few YT videos but it's still not fully explained. I would love to avoid making this mistake right now and avoid rewriting my logic later.


import React from 'react';

// do something


import React from 'react';

// do something else


import File1 from './file1';
import File2 from './file2';

// do something with both

  • Is it smart enough? Can I import same module as much as I want and it imports it only once?
  • What if I need to import React to File3 too? Is it still smart enough to handle this situation?

Im using Node, Babel and Webpack.


当您通过Node导入模块时(通过扩展,Webpack,因为它在模块解析时有效遵循相同的规则) ,文件中的代码执行一次,然后缓存生成的导出。 这意味着在两个文件中, React </ code>将是对同一对象的引用。 所以你的假设是正确的 - Webpack确实非常聪明,每次导入时都不会执行React的完整源代码文件。</ p>

你可以很容易地自己测试一下 - 添加一个 console.log()</ code>到在应用程序中的多个位置导入的模块(确保它不在函数或其他任何会推迟执行的模块中)。 您会看到日志只发生一次,而不是每次导入一次!</ p>

更新:</ strong>还值得注意的是 ES2015模块的规范有效地将此列为任何实现的要求:</ p>

如果正常完成,则此操作必须是幂等的。 每次使用特定的 referencingModule,说明符</ code>对作为参数调用它时,它必须返回相同的Module Record实例。 </ p>
</ blockquote>
</ div>



When you import a module through Node (and by extension, Webpack, as it effectively follows the same rules when it comes to module resolution), the code in the file is executed once, then the resulting exports are cached. This means that in both of your files, React will be a reference to the same object. So effectively your assumption is correct - Webpack is indeed smart enough to not execute React's full source code file every time you import it.

You can test this for yourself pretty easily - add a console.log() to a module that's imported in multiple places within your app (making sure it's not in a function or anything else that would defer its execution). You'll see that the log only happens once, rather than once per import!

Update: It's also worth noting that the spec for ES2015 modules effectively lists this as a requirement for any implementation too:

This operation must be idempotent if it completes normally. Each time it is called with a specific referencingModule, specifier pair as arguments it must return the same Module Record instance.

douxie9471 我喜欢你的测试设计的逻辑!
大约 2 年之前 回复
Csdn user default icon