Home > other >  Does 'import' in JavaScript fetch the whole file?
Does 'import' in JavaScript fetch the whole file?

Time:10-11

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:

<!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>

CodePudding user response:

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.

  • Related