ES6导入vs< script src>在html [英] ES6 import vs <script src> in html

查看:132
本文介绍了ES6导入vs< script src>在html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



1- 从xlibrarycomponent导入XLibraryComponent 从ES6



与常规方式



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



我问这个是因为我从React开始,您注入一些组件,从 中导入X $ ,并将其他组件注入到html中,作为我上面发布的第二种方式。



那么有什么区别?这是最好的方法?

解决方案

如果您在支持的浏览器(或其他环境)中使用实际的ES6模块他们,那是非常不同的。 这篇博客文章对差异有很好的了解。 p>

ES6规范包括大量关于模块加载的规则,允许模块稍微推迟,以支持循环依赖性和其他一些异常情况。



< script src =...>语法将同步包括一个脚本文件,一旦文件有已被加载。



您不能为真正的ES6模块使用脚本src 语法,因为它们是异步包含的,只有一次模块和任何依赖关系被加载才能被评估。



为了支持这种新的案例,但允许脚本包含在HTML中,一个新的 ;模块> 标签,其中包含要异步执行的代码,并支持模块依赖。



请注意,如果您请使用Req uireJS或类似的模块加载器polyfill型解决方案,因为您的 import 将被转换为对加载程序的调用。然后,加载程序将使用适当的来源创建一个脚本标签,并使用一个回调系统来模拟模块加载过程。


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?

解决方案

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.

这篇关于ES6导入vs&lt; script src&gt;在html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆