What is the "module" value for in the type property of the HTML <script> element

Asked

Viewed 419 times

4

I recently saw a code that includes a file Javascript was set the attribute type with the value module as in the example below:

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

I would like to know what this value is for, therefore, this question brings another within itself:

  • Browser compatibility

2 answers

5

The module is a new feature in Ecmascript 6th edition (ES6). When you arrow the attribute type="module" to an archive .js, you turn it into a módulo.

A module is a normal JS file, but with some peculiarities:

  • The code of a module automatically wins "use strict";, even if you don’t define it in him;
  • You can use the methods import and export in modules to exchange objects such as function, class, var, let, or const.

Everything that is declared inside a module, by default, is local to the module. If you want something declared in a module to be public, so that other modules can use it, you must export this feature (export), and for another module to use it, you must import it (import).

As to compatibility, the MDN shows the following table:

inserir a descrição da imagem aqui

On the same page you are informed:

This Feature is only just Beginning to be implemented in browsers natively at this time. It is implemented in Many transpilers, such as Typescript and Babel, and bundlers such as Rollup, Webpack and Parcel.

Free translation:

This feature is just starting to be implemented natively in the browsers at this time. It is implemented in several transpilators, like Typescript and Babel, and groupings like Rollup, Webpack and Parcel.

4

Javascript modules allow a program to be divided into multiple sequences of statements. Each module explicitly identifies the statements it uses that need to be provided by other modules and which of its statements are available for use by other modules.

In HTML5-compatible browsers the code is treated as a Javascript module. Processing the content of script is not affected by charset and Defer attributes. For information about using the module see here: https://hacks.mozilla.org/2015/08/es6-in-depth-modules/

Chrome documentation on the subject: https://www.chromestatus.com/feature/5365692190687232

Mozilla documentation on the subject: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

Demo: https://paulirish.github.io/es-modules-todomvc/

About browser compatibility see how Standards is doing: https://html.spec.whatwg.org/multipage/scripting.html#the-script-element (last updated on 7 March 2018)

inserir a descrição da imagem aqui

https://caniuse.com/#feat=es6-module

Browser other questions tagged

You are not signed in. Login or sign up in order to post.