简体   繁体   English

ES6 导入重复项?

[英]ES6 import duplicates?

I'm trying to keep my code (server 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.我尝试从这里搜索,我阅读了热门博客文章,甚至看了一些 YT 视频,但仍然没有完全解释。 I would love to avoid making this mistake right now and avoid rewriting my logic later.我很想现在避免犯这个错误,并避免以后重写我的逻辑。


File1文件 1

import React from 'react';

// do something

File2文件2

import React from 'react';

// do something else

File3文件 3

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?如果我也需要import React File3怎么办? Is it still smart enough to handle this situation?它仍然足够聪明来处理这种情况吗?

I'm using Node, Babel and Webpack.我正在使用 Node、Babel 和 Webpack。

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.当您通过 Node 导入模块时(扩展名为 Webpack,因为它在模块解析方面有效地遵循相同的规则),文件中的代码执行一次,然后缓存生成的导出。 This means that in both of your files, React will be a reference to the same object.这意味着在你的两个文件中, React都是对同一个对象的引用。 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.所以实际上你的假设是正确的——Webpack 确实足够聪明,不会在每次导入时执行 React 的完整源代码文件。

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).您可以很容易地自己测试它 - 将console.log()添加到在您的应用程序的多个位置导入的模块中(确保它不在函数中或其他任何会延迟其执行的地方)。 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:更新:同样值得注意的是, ES2015 模块的规范也有效地将其列为任何实现的要求:

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.每次使用特定的referencingModule, specifier对作为参数,它必须返回相同的模块记录实例。

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

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