5

If there has a common file named common.js, and others such as a.js, b.js...

common.js

const Common = { property: 'initial' }
export { Common };

a.js

import { Common } from 'common.js';
Common.property = 'changed';

b.js

import { Common } from 'common.js';
console.log(Common.property);

First, a.js runs and load the common.js into memory.

Then, b.js run by engine.

  1. Does the common.js will load again or use the existing common.js in the memory?
  2. If common.js was updated by other xx.js script, how will the import behave?
junlin
  • 1,835
  • 2
  • 25
  • 38
  • 1.2 2. => 1. ... ;) – Jonas Wilms Aug 11 '17 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 Aug 11 '17 at 18:18

2 Answers2

9

I'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:

  1. The module is cached so you are changing the same object
  2. It will print the the last value assigned
    • for example changed if a.js was executed
    • if only b.js is executed, then it will print initial

Try it out online here.

styfle
  • 22,361
  • 27
  • 86
  • 128
  • Thanks very much! I had understand. By the way, I using JavaScript(ES6) and compiled to ES5. – junlin Aug 11 '17 at 16:02
0

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)

AnilRedshift
  • 7,937
  • 7
  • 35
  • 59