前端工程化

前端模块化(AMD,CMD,CommonJs,ES6)

2022-07-26  本文已影响0人  郝同学1208

文章序

总是会看到前端模块化的这几个技术,今天一次性整理,如有错误欢迎评论指正!

AMD

异步加载,依赖前置,前置依赖建议写在前引用,在所有模块加载完成后立即执行回调函数,用户体验好,不容易造成卡顿
需要引用require.js

//main.js
require.config({
  baseUrl: 'src/lib/js',
  paths: {
    'jquery': 'jquery.min',
    'lodash': 'lodash.min',
  }
}
require(['use'], function() {
  console.log('some code here');
});

//math.js
define(['lodash'], function (_) {
  function add(a, b) {
    return _.add(a, b);
  }
  return { add };
});

//use.js
require(['jquery', 'math'], function ($, math) {
  $('#sum').html = math.add(1, 2);
});

CMD

异步加载,依赖就近,按需加载,在require引用的地方执行代码,性能好
需要引用sea.js

//math.js
define(function(require, exports, module) {
  let $ = require('jquery.js');
  let add = fucntion(a, b) {
    return a + b;
  }
  exports.add = add;
}

//use.js
define(function(require, exports, module) {
  let math = require('./math');
  const res = math.add(1, 2);
}

CommonJs

同步加载,运行时加载执行,容易阻塞进程,造成卡顿,一般用在服务端Node开发中,输出拷贝值,原始值改变不影响引用值
需要引用node.js

//math.js
module.exports = {
  add: function(a, b) {
    return a + b;
  }
}

//use.js
const math = require('./math.js');
const res = math.add(1, 2);

ES6

同步加载,编译时加载执行,因此必须放在代码块最顶层,输出原始值的引用,因此原始值改变会影响引用值
需要使用ES6标准

//math.js
const add = function(a, b) {
  return a + b;
}
export { add };

//use.js
import { add } from './math';

const res = add(1, 2);
上一篇 下一篇

猜你喜欢

热点阅读