花十分钟彻底弄懂前端模块化规范

66 阅读2分钟

一、前言

模块化是前端领域发展的趋势之一,它的好处非常多:

  • 1、抽离公共代码,避免耦合
  • 2、隔离作用域,避免变量冲突
  • 3、便于开发和维护

二、常见的模块化规范

1、AMD

AMD 是 RequireJS 在推广过程中对模块定义的规范化产出。AMD 推崇依赖前置。

define(['./a', './b'], function(a, b) { 

  // 依赖必须一开始就写好
  a.doing()
  b.doing()

  const text = 'Hello';

  function say() {
    console.log('function say');
  }



  function main() {
    console.log(text);
    say();
  }

  return main;

})

2、CMD

CMD 是 SeaJS 在推广过程中对模块定义的规范化产出。CMD 推崇依赖就近。

define(function (require, exports, module) {

  var a = require('./a')
  a.doSomething()
  // 此处略去 100 行
  var b = require('./b') // 依赖可以就近书写
  b.doSomething()
  // ...

})

3、CommonJS

为服务器提供的一种模块形式的优化。nodeJS采用这种规范

// 暴露模块
module.exports = {
  plus,
  minus,
}

// 或使用exports, 相当于var exports = module.exports;

// 注意:不能直接给exports赋值;如果给module.exports赋值后,exports也会失效。
exports.plus = plus;
exports.minus = minus;
// 引用模块
var a = require('./a');

a.plus()
a.minus()

4、UMD [Universal Module Definition]通用模块的定义法

通用的模块化方式,首先判断是否支持AMD,再判断是否支持CommonJs,否则都没有的话,则使用全局变量的方式来实现。

(function(global, factory){
  if(typeof define === 'function' && define.amd){
    // 如果支持AMD规范
    define([], factory);

  } else if (typeof exports === 'object' && typeof module !== 'undefined') {
    // 如果支持CommonJS规范
    module.exports = factory()

  } else {
    // 全局变量的方式
    if (typeof globalThis !== 'undefined'){
      global = globalThis
    } else {
      global =  global || self
    }
    global.TOOLS = factory()
    
  }
})(this, function(){

  // 模块内容开始
  const text = 'Hello';
  function say() {
    console.log('function say');
  }

  function main() {
    console.log(text);
    say();
  }

  return main;
  // 模块内容结束
})

5、esm 【es6 module】

ES6 在语言标准的层面上,实现了模块功能。

// 暴露模块1
export var a = 1;
export var b = 2;

// or
export { a, b };

// 暴露模块2
export default { a, b }
// 引用模块1
import { a, b } from './moduleA';

// 引用模块2
import module from './moduleB';
console.log(module.a)
console.log(module.b)

以下为一个计划管理小程序,欢迎体验: