Featured image of post JS模块化规范

JS模块化规范

简介

模块化产生的背景

随着网站逐渐变成 " 互联网应用程序 " ,嵌入网页的javascript代码越来越庞大,越来越复杂

所以模块化成了迫切的需求

模块化规范

  • CommonJS模块化规范
  • ES6模块化规范

CommonJS规范

每个文件就是一个模块,有自己的作用域,在一个文件里面定义的变量,函数,类都是私有的,对其他文件不可见

  1. 创建 “module” 文件夹

  2. 在module/commonjs文件夹下创建 operation.js

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    // 工具类
    const add = function (a, b) {
      return a + b;
    };
    
    const reduce = function (a, b) {
      return a - b;
    };
    
    const multiplication = function (a, b) {
      return a * b;
    };
    
    const except = function (a, b) {
      return a / b;
    };
    
    // 导出给别人使用好了
    module.exports = {
      add,
      reduce,
      multiplication,
      except,
    };
    
  3. 创建test.js用以测试

    1
    2
    3
    
    const num = require("./operation.js");
    
    console.log(num.add(1, 2));
    
  4. 运行test.js,查看结果

  5. 小结

    CommonJS使用exports和require 来导出,导入模块

ES6规范

ES6使用exports和import来导出和导入模块

  1. 创建module/es6文件夹

  2. 创建src/userApi.js文件,导出模块

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    export default {
      getList() {
        // 在真实业务中,异步获取数据
        console.log("获取数据列表");
      },
      save() {
        console.log("保存数据");
      },
    };
    
  3. 创建src/userTest.js文件,导入模块

    1
    2
    3
    4
    
    import user from "./userApi";
    
    user.getList();
    user.save();
    

    此时程序无法运行,因为ES6的模块化无法在Node.js中执行,需要用Babel来编译为ES5

  4. 初始化项目

    1
    
    npm init -y
    
  5. 配置.babelrc

    1
    2
    3
    4
    
    {
      "presets": ["es2015"],
      "plugins": []
    }
    
  6. 安装转码器,在项目中安装

    1
    
    npm install --save-dev babel-preset-es2015
    
  7. 定义运行脚本,package.json中增加 “build”

    1
    2
    3
    
      "scripts": {
        "build": "babel src -d dist"
      },
    
  8. 执行命令转码

    1
    
    npm run build
    
  9. 运行程序

    1
    
    node dist/userTest.js