Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

javascript - 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. 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?

I'm using Node, Babel and Webpack.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...