Import duplicate ES6?

I am trying to keep my code (on the server and client side) as modular as possible, and this requires a lot of import and export, however I have an unanswered question.

I tried to search from here, I read thematic blog posts and even watched some YT videos, but this is still not fully explained. I would like to avoid this error 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 the same module as much as I want, and it imports it only once?
  • What if I need import React too, File3 ? Is it still smart enough to handle this situation?

I use Node, Babel and Webpack.

+15
source share
1 answer

When you import a module through Node (and, accordingly, through Webpack, since it actually follows the same rules as when resolving the module), the code in the file is executed once, then the resulting export is cached. This means that in both of your files, React will be a reference to the same object. So your assumption is true: Webpack is really smart enough not to run a full source React file every time you import it.

You can easily check this yourself - add console.log() to the module, which is imported in several places in your application (make sure that it is not included in the function or anything else that may delay its execution). You will see that the log is created only once, and not once per import!

Update: It is also worth noting that the specification for ES2015 modules actually lists this as a requirement for any implementation:

This operation should be idempotent if it completes normally. Each time it is called with a specific pair of referencingModule, specifier as arguments, it must return the same instance of a modular record.

+23
source

All Articles