跳到主要内容

AMD 模块化介绍

AMD 全称 Asynchronous Module Definition,异步模块定义

介绍​

AMD 官方介绍如下

THE PROBLEM
Web sites are turning into Web apps
Code complexity grows as the site gets bigger
Assembly gets harder
Developer wants discrete JS files/modules
Deployment wants optimized code in just one or a few HTTP calls

主要解决的问题有
过去的Web逐渐成为Web应用
随着网站的增大,复杂性也逐渐增加
组合代码变的更难
开发者想要将Js代码打散
部署想要最好的代码分割方式在一个或多个http调用中

以及 AMD 提出的解决方案

SOLUTION
Front-end developers need a solution with:

Some sort of #include/import/require
Ability to load nested dependencies
Ease of use for developer but then backed by an optimization tool that helps deployment

解决方案
前端开发人员需要一个解决方案
一些api,如include/import/requre
有能力去加载嵌套依赖
开发者可以简单的使用,同时被帮助部署网站的优化工具所支持

AMD 基础使用​

AMD 是一种规范,而Require.js属于该规范的实现

我们学习的就是Require.js,使用必须在页面先引入 Require.js

如果想要开始使用,首先学习的是 require 函数

第一个参数是依赖的模块数组,填写我们要依赖什么模块

第二个是加载依赖模块成功后,回调该函数,代码如下:

// 模块名即代表文件名
require(['jquery'],function($){
$(....)
})

在该示例中,如果应用程序有依赖项,则依赖项也会被同时加载,当所有 js 都在同一目录的时候,这是最简单的配置,但是可以正常运行

如果你想以其他方式或从 CDN 加载脚本,那么我们需要使用Require.js的配置项

配置路径只需要使用require.config,例子如下

require.config({
baseUrl: "path", // 根路径
paths: {
jquery: "libs/jquery", //模块名与实际文件名映射
},
});
提示

我们只需要简单了解即可,因为现代前端开发已经很少使用到 require 了

当我们使用 require()引用了依赖的时候,会引用对应的模块

而模块怎么定义呢?使用 define!

当我们在 require 引入对应的模块的时候,如果没有进行 require.config 配置映射文件

则会取寻找对应的 js 文件,在 js 内使用 define 函数来定义模块

//假设是hello.js则模块名是hello
define(function (require) {
const printHello = () => {
console.log("hello");
};
return {
printHello,
};
});

同时还有一个更简单办法,第一个参数是该模块的模块名,第二个参数是define所需的依赖,其中require可以动态引用模块,而exports则是导出当前模块所需要导出的方法名,即等价于为hello暴露出去了方法。

define("hello", ["require", "exports", "otherModule"], function (
require,
exports,
otherModule
) {
exports.otherFunc = () => {
require("dynamicOtherModule").run(otherModule);
};
exports.printHello = () => {
console.log("hello");
};
});

引用文章​

AMD模块化规范介绍及使用

前端模块化:CommonJS,AMD,CMD,ES6

WHY AMD?

CommonJS 的 AMD规范

AMD define函数