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.
common.js
will load again or use the existing common.js
in the memory?common.js
was updated by other xx.js
script, how will the import
behave?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.
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.
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.
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:
changed
if a.js
was executedb.js
is executed, then it will print initial
Try it out online here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With