最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ES6 import a file in multiple place, why the file loads once? - Stack Overflow

programmeradmin1浏览0评论

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.

  1. Does the mon.js will load again or use the existing mon.js in the memory?
  2. If mon.js was updated by other xx.js script, how will the import 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.

  1. Does the mon.js will load again or use the existing mon.js in the memory?
  2. If mon.js was updated by other xx.js script, how will the import behave?
Share Improve this question asked Aug 11, 2017 at 15:25 junlinjunlin 2,0452 gold badges29 silver badges40 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 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.

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)

发布评论

评论列表(0)

  1. 暂无评论