I still don’t understand why on every import the module is not exporting a new store…isn’t this…

That is a great question and I think it’s one of the more interesting aspects of modules in JavaScript. The answer is createStore would run only once (providing that module is in one bundle of JavaScript and not duplicated into another bundle). In other words, say I have a file named myObject.js containing this code:

export default {};

Then require that module in two other files like so:

import myObject from ‘./myObject’;

myObject.a = 10;

import mObject from ‘./myObject’;

myObject.b = 20;

If you debug that, you’ll observe that the object exported in myObject.js is the same exact object that the two modules see on import. I like to think about it as the export is really a reference to an object and each consumer is getting the same reference!

It is more typical to export say a class and then use that class definition to make new instances of the class. In that case, the new instances are of course unique and not the same reference. But say you wanted a singleton — you can easily do that with JavaScript modules:

import MyClass from ‘./myClass’;

export default new MyClass();

The potential buggy spot here is if one day you decide to split up your build into multiple JavaScript bundles. For example, on one project, I have a vendor and non-vendor bundle because the vendor dependencies don’t change often while my code does. I could introduce a bug if I required the same singleton into each bundle yet didn’t mark one bundle as having that module as an external. In that case, each bundle would have it’s own singleton so there would be two “singletons” active at once.

With that said, I’ve never hit that issue. It would be very confusing though so it’s useful to know exactly how JavaScript modules work.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.