引入
模塊的規(guī)范
有了模塊,我們可以更方便的使用別人的代碼,想要什么功能,就加載什么模塊。
JavaScript的模塊規(guī)范有兩種:CommonJS 和 AMD。
- CommonJS
node.js的模塊系統(tǒng),就是參照CommonJS規(guī)范實(shí)現(xiàn)的。 在CommonJS中,有一個全局性方法 require(),用于加載模塊
例如有個數(shù)學(xué)模塊math.js,就可以像下面這樣加載
var math =require('math');
- 瀏覽器環(huán)境
對于服務(wù)器端:所有模塊都存放在本地硬盤,可以同步加載完成,等待時(shí)間就是硬盤的讀取時(shí)間
對于瀏覽器:模塊都在服務(wù)器端,等待時(shí)間取決于網(wǎng)速的快慢,可能要等很長時(shí)間,瀏覽器處于 假死 狀態(tài)
因此,瀏覽器端的模塊,不能采用“同步加載”(sync),只能采用“異步加載”(asyn)。 這就是AMD規(guī)范誕生的北京
- AMD(Asynchronous Module Definition)
“異步模塊定義”
它采用異步方式加載模塊,模塊的加載不影響它后面語句的運(yùn)行。
所有依賴這個模塊的語句,都定義在一個回調(diào)函數(shù)中,等到加載完成后,這個回調(diào)函數(shù)才會執(zhí)行。
require,import 的區(qū)別
- 形式不同
require/exports 的用法只有以下三種簡單的寫法:
const fs = require('fs')
exports.fs = fs
module.exports = fs
而 import/export 的寫法就多種多樣:
import fs from 'fs'
import {default as fs} from 'fs'
import * as fs from 'fs'
import {readFile} from 'fs'
import {readFile as read} from 'fs'
import fs, {readFile} from 'fs'
export default fs
export const fs
export function readFile
export {readFile, read}
export * from 'fs'
- 本質(zhì)區(qū)別
1.CommonJS還是ES6 Module輸出都可以看成是一個具備多個屬性或者方法的對象
2.default 是ES6 Module所獨(dú)有的關(guān)鍵字,export default fs 輸出默認(rèn)的接口對象,import fs from ‘fs’ 可直接導(dǎo)入這個對象
3.ES6 Module中導(dǎo)入模塊的屬性或者方法是強(qiáng)綁定,包括基礎(chǔ)類型;而CommonJS則是普通的值傳遞或者引用傳遞
3看個例子
// counter.js
exports.count = 0
setTimeout(function () {
console.log('increase count to', ++exports.count, 'in counter.js after 500ms')
}, 500)
// commonjs.js
const {count} = require('./counter')
setTimeout(function () {
console.log('read count after 1000ms in commonjs is', count)
}, 1000)
//es6.js
import {count} from './counter'
setTimeout(function () {
console.log('read count after 1000ms in es6 is', count)
}, 1000)
分別運(yùn)行
? test node commonjs.js
increase count to 1 in counter.js after 500ms
read count after 1000ms in commonjs is 0
? test babel-node es6.js
increase count to 1 in counter.js after 500ms
read count after 1000ms in es6 is 1
自我理解:require相當(dāng)于淺拷貝,相當(dāng)于重新創(chuàng)建了對象
而import相當(dāng)于賦值,賦值得到的只是將指針改變。不能在去賦值
(8.2 自我充電)