Using JavaScript modules in browsers 3:About file extensions

You may have noticed that we use. mjs as the file extension when writing module code. Of course, in the web, as long as the JavaScript MIME typetext/JavaScript field is provided in the HTTP response header, the file extension is not particularly important.

Moreover, the browser can determine whether this is a JS module by using the type attribute on the<script>tag.

However, we still recommend using. mjs as the file extension for two reasons:

  • In development, we can easily identify a file as a module rather than a regular script file through its extension (it doesn’t always work just by looking at the code). As mentioned earlier, browsers treat module code and regular script files completely differently.
  • Complies with the node.js specification. The nodeJs experimental module only supports files with the. mjs extension.

Module specifiers

When we use import, the string used at the end to indicate the module location is called module specifications or import specifications. In our previous example, the module specification was’/ Lib. mjs’.

In browsers, module descriptors have some limitations.

At present, bare modules are not supported (referring to being introduced only through package names in nodes). This regulation allows browsers to allow custom module loaders to assign special meanings to empty module descriptors like the one below.

The following citation methods are legal.

So far, the module descriptor must be a complete URL or use/.// The relative URL at the beginning.