Open panzerdp opened 3 years ago
Comment written by Patrick Mualaba on 05/16/2020 19:11:46
Thanks for the great explanation. Question: When a module is imported multiple times in different files and in different folders, I assume that it will not influence the evaluation, since the paths are first resolved to absolute paths i assume? Second: Does the same apply when using named imports (for example function references are strictly equal no matter where they are imported )?
Comment written by Dmitri Pavlutin on 05/19/2020 17:37:45
You're welcome @patrick_mualaba:disqus.
If multiple paths access the same module, anyways, the module is evaluated just once. Yep, it applies to default and named imports.
Comment written by Balázs Botond on 10/16/2020 12:44:10
Thanks for the excellent explanation!
Comment written by Dmitri Pavlutin on 10/16/2020 13:12:29
You're welcome Balazs!
Comment written by Suresh Babu on 10/21/2020 16:51:17
Awesome Dmitri Pavlutin.
Comment written by Dmitri Pavlutin on 10/21/2020 17:05:04
Thanks Suresh Babu.
Does this module resolution mechanism change when the modules are bundle by Webpack for instance?
Does this module resolution mechanism change when the modules are bundle by Webpack for instance?
Most likely not.
Hello thanks for the explanation. Don't you name the dynamic imports, it works the same way?
That's actually my wondering, too. Thank you.
So I've dug a little more into it and found out sth that may help with your understanding.
lib.js
let a = 1;
console.log('hi');
export default a;
export function fn(n) { ++a; return a + n }
app.js
import { default as b, test as fn1 } from './lib';
import { default as c, test as fn2 } from './lib';
console.log(b, c);
console.log(fn(9));
console.log(b, c);
console.log(fn2(9));
console.log(b, c);
And the output is:
hi
1 1
11
1 1
12
1 1
I'll explain some behavior in the code above:
import default a
as module.exports.a = a
, which will store a clone of but is irrelevant to a
. However, if a
is an object, the result will be increased.console.log
will only be called once.What an excellent, didatic, concentrated explanation of how the import statement works in modern Javascript. Thanks Dmitri, this was very helpful!
What an excellent, didatic, concentrated explanation of how the import statement works in modern Javascript. Thanks Dmitri, this was very helpful!
Thanks @italomg! Glad you like the post.
Written on 03/03/2020 12:14:32
URL: https://dmitripavlutin.com/javascript-module-import-twice/