个人博客: Javascript Module
javascript语言早期并没有模块的概念,这就导致了不同的解决方案涌现而出.
一、概念
- module: 用来将可以复用的代码进行封装,方便后续应用中其他模块使用.
- module format: 不同的方式使用不同的格式来定义模块和引用模块
- module loader: 用来在运行时解析和加载模块
- module bundler: 用来替换
module-loader
,在build阶段将所有的依赖都打包成bundler文件
二、格式
下面是几个被大家熟知和使用的格式:
- AMD(Asynchronous Module Definition):在浏览器端使用,使用
define
函数来定义模块 - CommonJS(CJS):该格式主要使用在nodejs环境下,使用
require
和module.exports
来定义依赖和模块,npm生态使用的都是该格式 - ES Module(ESM): ES2015标准中,Javascript首次定义原生的模块格式,通过
export
关键字导出模块的public api,通过import
关键字来导入依赖 - Universal Module Defintion(UMD):该格式可以被用在浏览器和nodejs环境下,适用于模块需要被多种类别的loader进行模块加载
- System.register:该格式用来在ES5环境下支持ES6的模块化,主要通过
systemjs
工具来完成,参考: github systemjs
2.1 CommonJS
通过exports
和require
关键字来定义和引用模块.
示例:
// user.js
const name = 'jiangjian';
const age = 18;
const sayHi = () => console.log('hi');
exports.name = name;
exports.age = age;
exports.sayHi = sayHi;
// index.js
const jiangjian = require('./user');
console.log('name is %s, age is %d', jiangjian.name, jiangjian.age);
jiangjian.sayHi();
//执行结果
$ node index.js
name is jiangjian, age is 18
hi
如果模块当中只有一个对象需要导出,可以直接将该值作为默认的导出对象,此时使用module.exports
示例:
// car.js
class Car {
constructor(name, price) {
this.name = name;
this.price = price;
}
getCarStat() {
return `Name: ${this.name}, Price: ${this.price}`;
}
}
module.exports = Car;
// index.js
const Car = require('./car');
const nio = new Car('蔚来', '40w');
console.log(nio.getCarStat());
$ node index.js
Name: 蔚来, Price: 40w
exports
VS module.exports
exports
和module.exports
指向的都是一个对象,即module
对象的exports
属性值
我们来了解一下module对象的属性情况
Module {
id: 'F:\\tmp\\nodejs\\car.js',
exports: [Function: Car],
parent:
Module {
id: '.',
exports: {},
parent: null,
filename: 'F:\\tmp\\nodejs\\index.js',
loaded: false,
children: [ [Circular] ],
paths:
[ 'F:\\tmp\\nodejs\\node_modules',
'F:\\tmp\\node_modules',
'F:\\node_modules' ] },
filename: 'F:\\tmp\\nodejs\\car.js',
loaded: false,
children: [],
paths:
[ 'F:\\tmp\\nodejs\\node_modules',
'F:\\tmp\\node_modules',
'F:\\node_modules' ] }
2.2 ES Module
格式:
// math.js
function add(a, b) {
return a + b;
}
function substract(a, b) {
return a -b;
}
export {add, substract}
//index.js
import {add, substract} from './math.js';
console.log(add(1, 1))
console.log(substract(2, 1));
//index.html
<html>
<body>
<script type="module" src="./index.js"></script>
</body>
</html>
执行结果:
了解更多,请扫描查看: