JavaScript模块化编程之AMD

7次阅读

共计 1547 个字符,预计需要花费 4 分钟才能阅读完成。

简单的说一下 AMD 是 ”Asynchronous Module Definition” 的缩写,意思就是 ” 异步模块定义 ”。它采用异步方式加载模块,模块的加载不影响它后面语句的运行。所有依赖这个模块的语句,都定义在一个回调函数中,等到加载完成之后,这个回调函数才会运行。
require.js 作用

实现 js 文件的异步加载,避免网页失去响应;
管理模块之间的依赖性,便于代码的编写和维护。

首先引入 requireJS 文件,并在 script 标签上指定入口文件 (主模块):
<head>
<meta charset=”UTF-8″>
<title>javascript 模块化编程 </title>
</head>
<body>
<script type=”text/javascript” src=”https://cdn.bootcss.com/require.js/2.3.5/require.js” defer async data-main=”js/main.js”></script>
</body>
接下来需要对 main.js 进行一些配置:
// 模块加载的配置
require.config({
// 基目录 如果每个模块不在一个基目录
// 不使用 baseUrl 直接在 paths 中具体指定
baseUrl: “lib”,
paths: {
‘jquery’: ‘jquery’,
‘vue’: ‘vue.min’,
‘pagination’: ‘my-pager’
},
// shim 属性 专门用来配置不兼容的模块 每个模块要定义:
// (1) exports 值(输出的变量名)表明这个模块外部调用时的名称
// (2) deps 数组 表明该模块的依赖性
// 比如 jq 的插件可以这样定义
shim: {
‘jquery.scroll’: {
deps: [‘jquery’],
exports: ‘jQuery.fn.scroll’
}
}
// requireJS 还有一系列插件 不再赘述
// [Plugins](https://github.com/requirejs/requirejs/wiki/Plugins)
});
// 主模块依赖于其它模块,这时就需要使用 AMD 规范定义的 require() 函数
// require([modules], function (modules) {});
require([‘jquery’, ‘vue’, ‘pagination’], function ($, Vue, pagination) {
console.log($);
console.log(Vue);
console.log(pagination);
});
关于自己定义符合 AMD 规范的模块,比如上面例子中的 pagination:
(function (factory) {
if (typeof exports === ‘object’) {
// Node/CommonJS
factory(require(‘document’), require(‘window’));
} else if (typeof define === ‘function’ && define.amd) {
// AMD
define(factory(document, window));
} else {
// Browser globals
factory(document, window);
}
}(function (document, window) {
var Test = {
a: 1
}
if (typeof module != ‘undefined’ && module.exports) {
module.exports = Test;
} else if (typeof define == ‘function’ && define.amd) {
define(function () {return Test;});
} else {
window.Test = Test;
}
}));

正文完
 0