在 JS 模塊化編程的模塊引入上, 主要有兩種方式:
- CommonJS 模塊標准
- ES6 moduel 特性
1. CommonJS
模塊引入:require()
模塊導出:exports 或者 module.exports
exports 與 module.exports 區別
1.1 exports 方式:
a.js(導出):
const name = 'cedric'
exports.name = name
b.js(引入):
const a = require('./a.js')
console.log(a) // { name: 'cedric' }
// 或者
// const { name } = require('./a.js')
// console.log(name) // 'cedric'
1.2 module.exports 方式:
- 方式一(不推薦):
a.js(導出):
const name = 'cedric'
module.exports = name
b.js(引入):
const name = require('./a.js')
console.log(name) // 'cedric'
- 方式二(推薦):
a.js(導出):
const name = 'cedric'
module.exports = {
name
}
b.js(引入):
const a = require('./a.js')
console.log(a) // { name: 'cedric' }
// 或者
// const { name } = require('./a.js')
// console.log(name) // 'cedric'
1.3 注意:
exports
返回的是模塊函數,module.exports
返回的是模塊對象本身,返回的是一個類- CommonJS 方式普遍用於node中模塊的編寫
- 一個模塊文件中可以有多個exports輸出,但只能有一個module.exports輸出
1.4 當有多個變量或函數需要輸出時:
使用 exports
a.js:
const name = 'cedric'
const age = 18
function fun () {
console.log('abc')
}
exports.name = name
exports.age = age
exports.fun = fun
b.js:
const a = require('./a.js')
a.fun() // abc
console.log(a) // { name: 'cedric', age: 18, fun: [Function: fun] }
使用 module.exports
a.js:
const name = 'cedric'
const age = 18
function fun () {
console.log('abc')
}
module.exports = {
name,
age,
fun,
}
b.js:
const a = require('./a.js')
a.fun() // abc
console.log(a) // { name: 'cedric', age: 18, fun: [Function: fun] }
2. ES6 moduel
- 模塊引入:import
- 模塊導出:export 或者 export default
2.1 注意
- 在一個文件或模塊中,
export
可以有多個,export default
只能向外暴露一次 - 通過
export
方式導出,在導入時要加{ },export default
則不需要 - Node 不支持 ES6 moduel 特性,解決方法是用 babel 編譯
export與export.defult的區別
2.2 export
a.js(導出):
export const name = 'cedric'
export function fun () {
console.log('abc')
}
導入:
import { name, fun } from './a'
console.log(name) // cedric
console.log(fun) // fun: [Function: fun]
fun() // abc
2.3 export default
a.js(導出):
function fun () {
console.log('abc')
}
export default fun
// 或者:
// export default function fun () {
// console.log('abc')
// }
導入:
import fun from './a'
console.log(fun) // fun: [Function: fun]
fun() // abc
關於export default 中的 default
實際上,a.js 文件的 export default
輸出一個叫做 default
的變量,所以,當import
的模塊引入 a.js 時,系統允許你為它取任意變量名。所以,如下一般會使用方式:
a.js(導出):
export default () => {
console.log('abc')
}
導入:
import 任意名稱 from './a'
console.log(任意名稱) // () => { console.log('abc'); }
任意名稱() // abc