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

标签 javascript javascript-framework js-amd

关于 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/

相关文章:

javascript - 等待NodeJS返回值

javascript - 使用 Requirejs 动态加载语言环境文件

javascript - 在 AMD 模块中使用条件依赖是个好主意吗?

javascript - 如何通过javascript获取 'Content-Length'?

javascript - 在手机上使用 window.location.hash 和 anchor 标签

javascript - jQuery hide() 或 fadeOut() 不起作用

javascript - 使用站点范围与本地页面脚本时可能存在 JavaScript 框架版本冲突

javascript - Bootstrap、Angular.js 和 Ember.js 中使用的数据属性选项是否与 Unobtrusive Javascript 原则冲突?

用于在非 SPA 站点上构建可重用组件的 Javascript MVC 框架

javascript - 如何在 Dojo 1.7 中使用未压缩的文件?