前端模块规范化(2) CommonJs

1、CommonJS是nodejs在后端应用时使用的标准,该规范的主要内容是,模块必须通过module.exports 导出对外的变量或接口,通过 require() 来导入其他模块的输出到当前模块作用域中。
(1)require用来加载模块
(2) 通过exports和modul.exports来暴露模块中的内容
例:创建3个js,它们关系如下:
在这里插入图片描述
1.1、math.js
//注意commonjs在模块定义的变量只是模块内的变量,不是全局的,在每个模块内部,module变量代表当前模块。它的exports属性是对外的接口,将模块的接口暴露出去:module.exports

var PI = 3.14;

function multiple(num1, num2) {
	return num1 * num2;
}

function square(n) {
	return n * n;
}

module.exports = {
	PI: PI,
	multiple: multiple,
	square: square
}

1.2、s.js
//require中的结果就是main中exports出去的结果

var m = require('./math'); 

function circle(r) {
	return m.multiple(m.square(r), m.PI);
}

module.exports = {
	s_circle: circle
}

1.3、main.js

var s = require('./s');

console.log(s.s_circle(10));

1.4运行:在dos命令下
在这里插入图片描述
2、前端的webpack也是对CommonJS原生支持的。
1.1: 需用webpack将js文件打包:安装webpack

npm install webpack -g  //注:直接安装会安装最新版本的,打包js时要加-o
webpapck main.js  -o  output.js

//也可以直接指定版本安装:

 npm install [email protected] -g //打包文件就可以不加-o,也避免了打包文件时出现很多错误:
webpapck main.js output.js

1.2 打包后就可以在目录下看到output.js文件啦,然后创建index.html,引入output.js就可以在前端运行了。
index.html

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>

	<body>
		<script src="output.js"></script>
	</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_43846213/article/details/89433267