javascript html 中的 ES6 导入 vs <script src>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31708545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ES6 import vs <script src> in html
提问by Non
I want to know what is the difference between
我想知道有什么区别
1- import XLibraryComponent from 'xlibrarycomponent'
from ES6
1-import XLibraryComponent from 'xlibrarycomponent'
来自 ES6
vs the regular way
与常规方式
2- <script src="/X/Libray/Component/path"></script>
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.
我问这个是因为我从 React 开始,我看到你注入了一些组件,import X from 'x'
以及你注入到 html 中的其他组件,这是我上面发布的第二种方式。
So, what are the differences? and which is the best way?
那么,有什么区别呢?哪个是最好的方法?
回答by ssube
If you're using actual ES6 modules in a browser (or other environment) that supports them, those are very different. This blog articlehas a good writeup of the differences.
如果您在支持它们的浏览器(或其他环境)中使用实际的 ES6 模块,则它们非常不同。这篇博客文章很好地描述了这些差异。
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.
ES6 规范包含许多关于模块加载的规则,这些规则允许模块稍微延迟,以支持循环依赖和其他一些不寻常的情况。
The <script src="..."
> syntax will include a script file synchronously and evaluate the contents as soon as the file has been loaded.
该<script src="..."
>语法将同步包括脚本文件和文件已加载评估的内容,尽快。
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.
您不能将script src
语法用于真正的 ES6 模块,因为它们是异步包含的,并且仅在模块和任何依赖项已加载后才进行评估。
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.
为了支持这种新情况但允许将脚本包含在 HTML 中,<module>
引入了一个新标签,其中包含要异步执行的代码并支持模块依赖关系。
Note that none of this applies if you're using RequireJS or a similar module loader polyfill-type solution, since your import
s 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.
请注意,如果您使用 RequireJS 或类似的模块加载器 polyfill 类型解决方案,则这些都不适用,因为您的import
s 将变成对加载器的调用。然后加载器将script
使用适当的源创建一个标签,并使用回调系统来模拟模块加载过程。