JavaScript模块化编程之AMD

简单的说一下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;
 }
}));

原文地址:https://segmentfault.com/a/1190000016913752

猜你喜欢

转载自www.cnblogs.com/lalalagq/p/9940603.html
今日推荐