模块化是什么

所谓模块化,就是指根据功能的不同进行划分,每个功能就是一个模块。最终,一个完整的产品是由各个模块组合而成的

  • 独立性。可以针对一个模块单独进行设计、研发,相对工作量和难度变小。

  • 复用性。一些通用模块(例如登录或注册)可以被重复使用,而不用每次重新开发。

  • 解耦性。模块与模块之间,将相互影响降到最低,使得更换、升级或添加某个模块,不影响其他模块的工作。

  • 灵活性。通过选择和组合不同的模块,可以快速构建一个新的产品。

ES5中的模块化

  1. 函数的封装
    • 每个函数的作用域仅在内部有效
    • 函数作用域之间没有关系,低耦合
    • 污染全局命名空间
  2. 对象封装
    • 两个对象相互之间是独立的,低耦合
    • 全局与用语中可以随意修改
  3. 自调函数
    • 低耦合
    • 在全局作用域中无法访问自调函数内部的函数或方法
  4. 自调函数配合全局对象

ES6中的模块化

当使用JavaScript文件当作是一个模块

  • 当前JavaScript模块文件自动开启严格模式
  • 使用export命令将当前模块内容导出

export导出

1
2
3
4
5
6
7
var v = 100;
const c = 1000;
function fn() {
return "666";
}
export { v, c, fn };

import导入

1
2
3
import { v as n, c, fn } from "./9. ES6中的模块化-export";
// 允许使用别名
console.log(n, c, fn);

存在不支持的情况,所以运行可能失败。

RequireJS

  1. 引入requireJS

    1
    <script async='true' defer src="https://cdn.bootcdn.net/ajax/libs/require.js/0.10.0/require.min.js"></script>
    • async

      表示异步加载

    • defer

      兼容IE浏览器

  2. 引入主模块

    为上一步引入的script标签添加自定义属性data-main,其值为主模块。

    1
    2
    <script data-main="./requireJS/index.js" async='true' defer
    src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
  3. 定义模块

    编写模块用到的函数为define()函数,其定义方式有多种:https://www.html.cn/doc/requirejs/

    1
    2
    3
    4
    5
    // 模块文件

    define(function () {
    return "Hello RequireJS";
    });
  4. 引入模块

    利用require.config()函数对模块加载自定义

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    // 主模块
    // 对模块加载进行自定义
    require.config({
    paths: {
    hello: "./moudle",
    },
    });

    // 加载指定模块 - require(names,callback)
    // names: 数组类型 加载模块的名称
    // callback: 回调函数,将加载完毕的模块结果进行处理
    require(["hello"], function (value) {
    console.log(value);
    var h1 = document.createElement("h1");
    h1.textContent = value;
    document.body.appendChild(h1);
    });

    image-20201028095422941

SeaJS

官方网站:http://seajs.github.io/seajs/docs/

  1. 引入script标签

    1
    <script async='true' src="./seaJs/index.js"></script>
  2. 编写模块

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // 模块文件
    /**
    * @param {any} require 用于导入其他模块
    * @param {any} exports 用于导出当前模块
    * @param {any} moudle moudle.exports用于导出当前模块
    * @returns {any}
    */
    define(function (require, exports, moudle) {
    exports.hello = "Hellp SeaJS!";
    });
  3. 配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    seajs.config({
    bash: './seaJs/',
    paths: {
    moudle: 'moudle'
    },
    alias: {
    'hello': 'moudle'
    }
    })
    seajs.use('hello', function (value) {
    var h1 = document.createElement("h1");
    h1.textContent = value.hello;
    document.body.appendChild(h1);
    console.log(value);
    })