# js 模块化(commonjs、AMD、CMD、ES6)##

一 简介

1.什么是模块化

模块化简单来说就是将一个复杂的项目根据一些特定的规则(模块、功能、页面)封装成不同的模块,然后再合并在一起,内部功能实现私有化,向外部暴露方法进行通信

2.模块化的好处

1. 避免全局变量污染
2. 利于项目维护
3. 便于代码复用

3.模块化的规范

1. CommonJS
2. AMD
3. CMD
4. ES6

二 CommonJS 规范

1.说明

每个文件都可以作为一个模块,服务端是同步进行加载,浏览器需要编译(使用Browserify进行格式转换)之后才可以(浏览器引擎不认识,原因是浏览器缺少Node.js环境变量:module、exports、require、global)

2.基本语法

// 暴露模块
// 方式1 module.exports = value;
// 方式2 exports.xx = value;
​
// 引入模块
// 项目内模块 let xx = require('../../xx.js')
// 第三方模块 let xx = require('xx')

3. 基本示例

// a.js
module.exports = {
    name:'Hello World',
    foo(){
        console.log('a.js name:', this.name );
    }
}

// b.js
module.exports = function(){
    console.log('b.js');
}

// c.js
exports.foo = function (){
    console.log('c.js foo');
}
exports.bar = function (){
    console.log('c.js bar');
}
exports.name = 'Hello World !';
// main.js
let a = require('./a.js');
let b = require('./b.js');
let c = require('./c.js');
let _ = require('lodash');
​
console.log(a.name);       // Hello World
console.log(a.foo());      // a.js name: Hello World
console.log(b());          // b.js
console.log(c.foo());      // c.js foo
console.log(c.bar());      // c.js bar
console.log(c.name);       // Hello World !
console.log(_.add(6, 4));  // 10
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值