Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does 'import' in JavaScript fetch the whole file?

I am wondering about the practical use of ‘importing’ a .js file at the front end.

Say, we have a file module.js:

// module.js
export var a = 10;
var b = 20;

Now when we do the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!DOCTYPE html><html><body>
<script type="module">
    import {a} from "./module.js";
</script>
</body></html>

Does variable b get fetched over the internet and only discarded at the front end?

If variable b is discarded at the back end, how can the server tell what is needed and what is not?

If variable b is discarded at the front end, why don’t we just do the following?

<!DOCTYPE html><html><body>
<script src="./module.js"></script>
</body></html>

>Solution :

Yes, if you run that code in a browser, the entire file is transmitted across the network, parsed, and instantiated. That said, in both scripts and modules, the JavaScript engine may be able to identify dead code (like that b variable and its initialization) and discard it, if it seems worth the runtime cost of doing so, which it rarely is.

However, most bundlers (Webpack, Parcel, etc.) offer optional tree-shaking features they can apply to modules when building bundles. They do static analysis on the modules being bundled together and identify things that are definitely "dead wood" (hence "tree-shaking") and leave that code out of the bundle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading