Ad

Using System.js, Why Do Changes I Make To A Module In One File Persist In Another?

I'm in the beginning of a small web app, and have set it up to use JSPM and System.js for module loading. I have two files, app.js and util.js. In util.js, I am creating a function that gets a Handlebars template for me, and caches them in Handlebars.templates. The actual function has more to it than this, but lets say it just does this

import Handlebars from 'handlebars';
export function getTemplate(){ 
    Handlebars.templates = 'HELLO THERE';
}

Then, in app.js, I do this

import {getTemplate} from 'util.js'
import Handlebars from 'handlebars'
getTemplate();
console.info(Handlebars.templates) //"HELLO THERE"

Why does Handlebars.templates persist? Is this something System.js does? Something Handlebars does?

Ad

Answer

ES6 Modules are singletons. Even though the module is imported by isolated files they both refer to the same instance. This is the expected behavior and is possible because export and import rely on bindings rather than copying values.

Since you may be coming from a CommonJS background you might find "What do ES6 modules export?" to be a good explanation about the difference in behavior.

Ad
source: stackoverflow.com
Ad