I know that standard ECMAScript Modules are static and bindings are imported, not copies of values.
module.js
let age = 15
function doBirthday() {
console.log('module, age is', age)
age++
console.log('module, age after birthday is', age)
}
export { age, doBD }
main.js
import {age,doBirthday } from './module.js'
console.log('main, age is: ', age)
console.log('doBirhtday')
doBirthday()
console.log('main, age after birthday: ', age)
prints:
main, age is: 15
doBirhtday
module, age is: 15
module, age after birthday is: 16
main, age after birthday: 16 //value is updated from module' doBirthday
while using dynamic import in main.js
const { age, doBirthday } = await import('./module.js')
console.log('main, age is: ', age)
console.log('doBirhtday')
doBirthday()
console.log('main, age after birthday: ', age)
prints:
main, age is: 15
doBirhtday
module, age is: 15
module, age after birthday is: 16
main, age after birthday: 15 //as if age variable was not bonded to the one imported from module
I tried to look for an explanation of this two different behaviours but find none.
Can someone reference some documentation or explain what's the difference between this two ways of import in ES6 ?
If you create new identifiers with the import keyword (not the import function), those identifiers will be the same values exported by the other module:
import {age,doBirthday } from './fabio.mjs'
^^^^^^
If you create new identifiers with const, those identifiers will be plain variables, not inherently tied to whatever generated them, even if it came from a module:
const { age, doBirthday } = await import('./fabio.mjs')
^^^^^
The above is similar to doing
const fabioResult = await import('./fabio.mjs');
const { age, doBirthday } = fabioResult;
It's not an imported identifier anymore, only a plain variable whose value is taken from the object at the time of assignment.