dongxiongshi9952 2016-05-26 11:28
浏览 290
已采纳

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.

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

import React from 'react';

// do something else

File3

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.

  • 写回答

1条回答 默认 最新

  • douqiang1851 2016-05-26 11:38
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vc6.0中想运行代码的时候总是提示无法打开文件是怎么回事
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题