ES6导入重复? [英] ES6 import duplicates?

查看:154
本文介绍了ES6导入重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图保持我的代码(服务器端和客户端)尽可能的模块化,这需要大量的导入和导出,但是我有一个未回答的问题。

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.

我试图从这里搜索,我读了主题博客帖子,甚至看了几个YT视频,但它还没有完全解释。我现在很想避免这样的错误,并避免重写我的逻辑。

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.

File1

import React from 'react';

// do something

File2 / p>

File2

import React from 'react';

// do something else

File3

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

// do something with both







  • 足够聪明吗?我可以根据需要导入相同的
    模块,它只会导入一次?

  • 如果我需要 import React File3 呢?处理这种情况还不够聪明吗?


    • 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?
    • 我使用Node,Babel和Webpack。

      Im using Node, Babel and Webpack.

      推荐答案

      当您通过节点导入模块(并且通过扩展名Webpack导入模块,因为它在模块解析时实际遵循相同的规则),文件中的代码将被执行一次,然后导致结果导出被缓存。这意味着在您的两个文件中, React 将引用同一个对象。所以有效的假设是正确的 - Webpack确实足够聪明,不能每次导入React的完整的源代码文件。

      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.

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

      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!

      这篇关于ES6导入重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆