CommonJS 规范
CommonJS一般同于Node环境, 如服务端
初步上手
- 导出:
school.js
js
const name = '家里蹲大学'
const slogan = '吃饭, 睡觉, 打豆豆'
function getTel() {
return '010-987650321'
}
// 导出 / 暴露
export.name = name
export.slogan = slogan
export.getTel = getTel- 导出:
student.js
js
const name = '张三'
const motto = '法外狂徒'
function getHobby() {
return ['抽烟', '喝酒', '烫头']
}
// 导出 / 暴露
export.name = name
export.motto = motto
export.getHobby = getHobby- 导入:
index.js
js
// 导入 / 引入
const school = require('./school.js')
const student = require('./student.js')
console.log(school)
console.log(student)导出数据
在CommonJS标准中, 导出数据有两种方式:
module.exports = valueexports.name = value
注意
- 每个模块内部的
this,exports和module.exports在初始时, 都指向同一个空对象, 这个空对象就是当前模块导出的数据 - 无论如何修改导出对象, 最终导出的都是
module.exports的值 exports是对module.exports的初识引用, 仅为了方便给导出项添加属性, 所以不能使用exports = value的形式导出数据, 但是可以使用module.exports = xxx导出数据
示例和验证
- 两种导出方式
js
const name = '张三'
function getHobby() {
return ['抽烟', '喝酒', '烫头']
}
// 导出 / 暴露 方式一
export.name = name
export.getHobby = getHobby
// 导出 / 暴露 方式二
module.exports = {
name,
getHobby
}- 验证
this,exports和module.exports
js
console.log(this) // {}
console.log(exports) // {}
console.log(module.exports) // {}
console.log(this === exports && exports === module.exports) // true- 最终导出
js
exports { a: 1 }
exports.b = 2
module.exports.c = 3
module.exports = { d: 4 }
// 最终导出内容: { d: 4 }导入数据
在CommonJS模块化标准中, 使用内置的require函数进行导入数据
- 直接导入数据
js
const user = require('./user.js')- 引入同时解构出要使用的数据
js
const { name, gender, tel } = require('./user.js')- 引入同时解构 + 重命名
js
const { name: username, gender: sex, tel: mobile } = require('./user.js')
console.log(username, sex, mobile)扩展理解
一个JS模块在执行时, 是被包裹在一个内置函数中执行的, 所以每个模块都有自己的作用域
- 验证,
arguments.callee可以得到这个函数本身
js
console.log(arguments)
console.log(arguments.callee.toString())- 内置函数的形式
js
function(exports, require, module, __filename, __dirname) {
// 内容
}浏览器端运行
Node.js默认支持CommonJS规范, 但是浏览器端不支持, 所以需要经过编译才能使用
- 全局安装
browserify
bash
npm i browserify -g- 编译
bash
# index.js: 源文件
# -o: -output 输出
# build.js: 输出的目标文件
browserify index.js -o build.js- 使用
html
<script type="text/javascript" src="./build.js"></script>