Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 import a file in multiple place, why the file loads once?

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?
like image 330
junlin Avatar asked Aug 11 '17 15:08

junlin


People also ask

What will happen if a feature module is imported multiple times?

If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used. If a module is imported multiple times, but with the same specifier (i.e. path), the JavaScript specification guarantees that you'll receive the same module instance.

What is dynamic import in JavaScript?

Dynamic imports or Code Splitting is the practice of breaking up your JavaScript modules into smaller bundles and loading them dynamically at runtime to improve and increase the performance of your website dramatically.

How do JavaScript imports work?

Javascript import statement is used to import bindings that are exported by another module. Using import, the code is easier to manage when it is small and bite-size chunks. This is the thinking behind keeping functions to only one task or having files contain only a few or one component at a time.


1 Answers

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.

like image 139
styfle Avatar answered Oct 18 '22 21:10

styfle