ES6 import duplicates?

后端 未结 1 1436
鱼传尺愫
鱼传尺愫 2020-12-09 03:54

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.

<
相关标签:
1条回答
  • 2020-12-09 04:29

    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.

    0 讨论(0)
提交回复
热议问题