js模块化

commonJs
  • 定义模块:module.exports, 导出属性不需要声明变量
  • 定义模块:exports, exports 指向module.exports
  • 加载模块:require(), 将一个文件当作一个导出对象引入进来
  • 服务器端,node,运行时加载,模块对象拷贝

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

exports.add = function(a, b) {
    return a + b
}

// index.js
const common = require('./common.js')

common.add(10, 20)
ES Module
  • 定义模块:export, export default
  • 加载模块: import from
  • export导出属性需要声明变量
  • 浏览器端,es6,编译时输出接口,模块对象引用
// common.js
export function add(a, b) {
    return a + b
}

export default {
    add
}

// index.js
import common from './common.js'
import { add } from './common.js'

common.add(10, 20)
requireJs/AMD
  • 定义模块:define(id?, deps?, factory)
  • 加载模块:require([module], factory)
  • 浏览器端,异步加载,依赖前置
// common.js
define('common', ['utils', 'require', 'exports'], function(utils, require, exports) {
    exports.add = function(a, b) {
        return a + b
    }

    exports.utils = function() {
        return require('./util.js')
    }
})

// index.js
require(['common'], function(common) {
    common.add(10, 20)
})
SeaJS/CMD
  • 定义依赖: 无需列依赖
  • require, exports, module 顺序固定
  • 浏览器端,异步加载,依赖就近,
// common.js
define(function(require, exports, module) {
    exports.add = function(a, b) {
        return a + b
    }
})


// index.js
define(function(require) {
    const common = require('./common.js')
    common.add(10, 20)
})
动态加载/import()
  • 返回一个promise
import('./common.js').then(common => {
    common.add(10, 29)
})

const common = await import('./common.js')
common.add(10, 20)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值