前端模块化

CommonJs

CommonJs是一种JavaScript语言的模块化规范,它通常会在服务端的nodejs上使用,项目是由多个模块组成的,模块与模块之间的调用,需要各个模块有相同规范的API,这样一来在使用的过程中不会有那么多的学习成本,并且对于单个模块来说是类聚的。

在CommonJs的模块化规范中,每一个文件就是一个模块,拥有自己独立的作用域,变量,以及方法等,对其他的模块都不可见。

CommonJs规范规定,每个模块内部,module变量代表当前模块。这个变量是一个对象,它的exports属性(module.exports)是对外的接口。加载某个模块,其实是加载该模块的module.exports属性。require方法用于加载模块。

1
2
3
4
5
6
7
8
9
10
11
//module-a.js
module.exports = {
a:1
}

//module-b.js
var ma = require('./module-a.js')
var b = ma.a + 2
module.exports = {
b:b
}

Es Module

在Es Module中导出分为两种,单个导出(export)和默认导出(export default),单个导出在导入时不像CommonJs一样直接把值全部导入进来了,Es Module中可以导入我想要的值,那么默认导出就是全部直接导入。

1
2
3
4
5
6
7
8
9
10
11
12
//导出变量
export const name = 'cny'
export const age = 22

//导出函数
export const test = () => {}
export function () {}

//导出多个
const name = 'cny'
const age = 22
export {name,age}

export和export default 同时使用并不互相影响,只需要在导入的地方之一,如果文件里有混合导入,则必须先导入默认导出的,再导入当然导入的值

1
2
3
4
5
6
7
export const name = 'cny'
export cosnt age = 22

export default{
fn(){},
msg:'今天天气真好'
}

Es Module使用的是import语法进行导入,如果要单个导入则必须使用花括号{},花括号不代表解构赋值

1
2
3
4
5
6
7
8
9
10
//index.js
export const name = 'cny'
export const age = 22


import {name,age} from './index.js'

//如果里面全是单个导入的情况下
import * as all from './index.js'
console.log(all) //{name:'cny',age:22}