CommonJS
问题: 暴露的模块的本质到底是什么?
1.node基础_模块化
2.理解以下的:4. 模块化编码
问题: CommonJS两种实现的区别?
1.Node.js : 服务器端
2. Browserify : 浏览器端 也称为js的打包工具;browserify 只是在开发是用于打包 ;上线时不需要
Node.js模块化
- 下载安装node.js
- 创建项目结构
|-modules
|-module1.js
|-module2.js
|-module3.js
|-app.js
|-package.json
{
"name": "commonJS-node",
"version": "1.0.0"
}
- 下载第三方模块
- npm install uniq --save // 高版本的npm中–save是默认添加了
- 模块化编码
-
module1.js
// 暴露一个对象 module.exports = { foo() { console.log('moudle1 foo()') } }
-
module2.js
// 暴露一个函数;一个模块只能有一个module.exports module.exports = function () { console.log('module2()') }
-
module3.js
// 可以无限往 exports中添加属性和值 exports.foo = function () { console.log('module3 foo()') } exports.bar = function () { console.log('module3 bar()') }
-
app.js
module.exports = value; 直接将模块exports 对象部覆盖 exports.xxx = value; 可以往exports 对象中添加多个属性名和值
/** 1. 定义暴露模块: module.exports = value; exports.xxx = value; 2. 引入模块: var module = require(模块名或模块路径); */ "use strict"; //引用模块 let module1 = require('./modules/module1') let module2 = require('./modules/module2') let module3 = require('./modules/module3') let uniq = require('uniq') let fs = require('fs') //使用模块 对应不同的暴露方式及调用方式 module1.foo() module2() module3.foo() module3.bar() console.log(uniq([1, 3, 1, 4, 3])) fs.readFile('app.js', function (error, data) { console.log(data.toString()) })
- 通过node运行app.js
- 命令: node app.js
- 工具: 右键–>运行