CommonJS模块化教程
1.编写自定义模块
-
module1.js
const name = '赖' const age = 22 /* 使用module.exports = xxx暴露 module.exports和exports不能混用,若混用了,以module.exports为主 */ module.exports = { showName(){ console.log(name) }, showAge() { console.log(age) } }
-
module2.js
//使用exports.xxx暴露 exports.sum = function (a,b){ console.log(a+b) } exports.sub = function (a,b){ console.log(a-b) }
2.下载第三方模块
- 执行命令:
npm i uniq
3.主文件引入模块
-
app.js
//暴露的本质是module.exports的内容 //引入module1,引入的内容是什么,取决于暴露的是什么 const module1 = require('./module1.js')//引入自定义模块 /* module1.showName() module1.showAge() console.log(module1) */ const module2 = require('./module2.js')//引入自定义模块 /* module2.sum(1,2) module2.sub(1,2) console.log(module2.a) */ const uniq = require('uniq')//引入第三方模块 const arr = [2,3,4,5,6,1,8,7,9,2,3,4] console.log(uniq(arr))
4.运行app.js
1.【在Node环境下运行】,直接用命令:
node app.js
2.【在浏览器环境下运行】,需要如下操作:
全局安装Browserify
npm install browserify -g
编译指定文件
browserify app.js -o build.js
html页面中引入build.js
<script src="./build.js" type="text/javascript" charset="utf-8"></script>