CommonJS模块化教程

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值