gpt4 book ai didi

javascript - AMD : what is the purpose in javascript context?

转载 作者:行者123 更新时间:2023-12-01 07:42:50 25 4
gpt4 key购买 nike

关于 AMD(异步模块定义),我读到这样的阶段:

The AMD format comes from wanting a module format that was better than today's "write a bunch of script tags with implicit dependencies that you have to manually order" and something that was easy to use directly in the browser.



javascript上下文的目的是什么?你能举个例子吗?赞成和控制使用 AMD?

最佳答案

早在 JavaScript 获得原生模块系统之前,将脚本放到页面上的唯一方法是 <script>元素。这些按顺序执行,按照它们在 HTML 中出现的顺序。这意味着如果你的脚本依赖于 jQuery,那么 jQuery 的 <script>必须在脚本的 <script> 之前出现.否则,它会爆炸。

将应用程序逻辑拆分为多个文件的情况并不少见,尤其是随着应用程序的增长。但是使用这种手动排序脚本的系统很快就会变成一场噩梦。您的脚本具有隐式依赖关系,其管理在其他地方定义。这就是 AMD 的用武之地。

AMD 是一个模块规范,而 RequireJS 是这种系统的实现。简而言之,它是您代码的包装器,它 1) 在调用之前保持脚本惰性,2) 允许您的脚本显式定义其依赖项,以及 3) 允许模块系统计算出哪些依赖项以什么顺序执行。

这是一个粗略的例子:

// your-app.js
define(['jquery', 'underscore'], function($, _){
// Your script sits in this "wrapper" function.
// RequireJS now knows app.js needs jquery and underscore.
// It loads and executes them first before your script.
})

// jquery.js
define('jquery', [], function(){
// jQuery stuff
return jQuery
})

// underscore.js
define('underscore', [], function(){
// underscore stuff
return underscore
})

// Then on your HTML, load up your app.
<script data-main="path/to/app.js" src="path/to/require.js"></script>

关于javascript - AMD : what is the purpose in javascript context?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10160343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com