简体   繁体   中英

How actually ECMA-Script 2015 (and above) module loading through import statement works behind the scenes?

Since mostly we're using modules and import statement transpiling them with tools like Babel , I'm intrigued about how native Web browser's implementations will load external files with the so-called import statement.

Will modules be loaded using XmlHttpRequest / XmlHttpRequest2 under the hoods?

AFAIK, the whole standard defines a programmatic API as System global variable where there're methods like System.define to evaluate a JavaScript source code and register it as a named module.

Does this mean that actual module system implementation won't cover external file module loading (meaning that a library/framework or your own vanilla JavaScript code should get the source code using an XmlHttpRequest ?)

There is a loader standard being actively developed by the WHATWG that will handle the loading in the browser: http://whatwg.github.io/loader/

As this is still a work in progress, things might still change. As far as I can see, the exact way that the browser loads the files is not specified, but it is probable that it will use the Fetch API (the Promise-based replacement for XmlHttpRequest2).

In the end, you should be able to use the module syntax with script tags and the browser (or whatever your JS environment is) will handle the loading:

<script type="module">
  import x from 'y';
  import a from 'b';

  ...
</script>

or

<script type="module" src="y.js"></script>

Currently, browsers are at different points of implementation:

  • IE/Edge: Under Consideration
  • Firefox: In progress
  • Chrome: In progress
  • Webkit: Meta Bug

Please feel free to correct me or extend this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM