If there has a mon file named mon.js
, and others such as a.js
, b.js
...
mon.js
const Common = { property: 'initial' }
export { Common };
a.js
import { Common } from 'mon.js';
Common.property = 'changed';
b.js
import { Common } from 'mon.js';
console.log(Common.property);
First, a.js
runs and load the mon.js
into memory.
Then, b.js
run by engine.
- Does the
mon.js
will load again or use the existingmon.js
in the memory? - If
mon.js
was updated by otherxx.js
script, how will theimport
behave?
If there has a mon file named mon.js
, and others such as a.js
, b.js
...
mon.js
const Common = { property: 'initial' }
export { Common };
a.js
import { Common } from 'mon.js';
Common.property = 'changed';
b.js
import { Common } from 'mon.js';
console.log(Common.property);
First, a.js
runs and load the mon.js
into memory.
Then, b.js
run by engine.
- Does the
mon.js
will load again or use the existingmon.js
in the memory? - If
mon.js
was updated by otherxx.js
script, how will theimport
behave?
- 1.2 2. => 1. ... ;) – Jonas Wilms Commented Aug 11, 2017 at 15:30
- @torazaburo I thought this was a duplicate at first but it is not, just related. The linked question is about the code inside the module being executed. This question is about the an object returned from a module being mutated. – styfle Commented Aug 11, 2017 at 18:18
2 Answers
Reset to default 9I'm assuming you are using Node.js so the import
will turn into require
statements after transpiling.
From the docs:
Modules are cached after the first time they are loaded. This means (among other things) that every call to
require('foo')
will get exactly the same object returned, if it would resolve to the same file.
Source
To answer you questions explicitly:
- The module is cached so you are changing the same object
- It will print the the last value assigned
- for example
changed
ifa.js
was executed - if only
b.js
is executed, then it will printinitial
- for example
Try it out online here.
Node != ES2015.
Specifically, and rather especially, the import system from ES2015 is different the require syntax from Node.
ES2015 does not allow you to change the shape of a module during runtime - the code is static while this is built up in memory.
As to what a practical implementation might do is up to question, but the TL;DR is that you should not change a file in between module loads or bad things may happen (TM)