Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 import vs <script src> in html [duplicate]

I want to know what is the difference between

1- import XLibraryComponent from 'xlibrarycomponent' from ES6

vs the regular way

2- <script src="/X/Libray/Component/path"></script>

I am asking this because I am starting with React, I see that you inject some components doing import X from 'x' and with other components you injected into the html as the second way I post above.

So, what are the differences? and which is the best way?

like image 318
Non Avatar asked Jul 29 '15 18:07

Non


People also ask

Can you have multiple script sources in HTML?

Multiple <SCRIPT> TagsYou can have as many <SCRIPT></SCRIPT> tags as you would like in a document. The <SCRIPT> tags are processed as they are encountered.

Can I use import in script tag?

In order to use the import declaration in a source file, the file must be interpreted by the runtime as a module. In HTML, this is done by adding type="module" to the <script> tag.

Is ES6 import asynchronous?

ES6 module loaders will be asynchronous while node.

What is script src in HTML?

The src attribute specifies the URL of an external script file. If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again. Save the script file with a .


1 Answers

If you're using actual ES6 modules in a browser (or other environment) that supports them, those are very different. This blog article has a good writeup of the differences.

The ES6 spec includes a number of rules around module loading that allow for modules to be somewhat deferred, to support circular dependencies and some other unusual cases.

The <script src="..."> syntax will include a script file synchronously and evaluate the contents as soon as the file has been loaded.

You cannot use the script src syntax for a real ES6 module, as they are included asynchronously and evaluated only once the module and any dependencies have been loaded.

To support this new case but allow scripts to be included in HTML, a new <module> tag has been introduced, which contains code to be executed asynchronously and supports module dependencies.

Note that none of this applies if you're using RequireJS or a similar module loader polyfill-type solution, since your imports will be turned into calls to the loader. The loader will then create a script tag with the appropriate source and use a system of callbacks to simulate the module loading process.

like image 156
ssube Avatar answered Oct 04 '22 01:10

ssube