翻譯github整理筆記。模塊(能力一般水平有限)。
ps:在ES6模塊系統(tǒng)中,js自動將模式變?yōu)閲?yán)格模式
export
- 在CommonJS,你可以利用將屬性賦給 module.exports 來實現(xiàn)將屬性輸出??梢钥吹?,在下面的代碼快中,你可以輸出對象,數(shù)組,函數(shù),變量中的任何一個
module.exports = 1
module.exports = NaN
module.exports = 'foo'
module.exports = { foo: 'bar' }
module.exports = ['foo', 'bar']
module.exports = function foo () {}
ps: 任何一個在module中定義的變量不會提供給其他模塊,除非被特定指出輸出,作為一個模塊的api
- 你可以吧CommonJS中的 module.exports = 簡寫成 export default
export default 1
export default NaN
export default 'foo'
export default { foo: 'bar' }
export default ['foo', 'bar']
export default function foo () {}
- 不同于CommonJS export 表達式必須寫在最高作用域內(nèi),即使當(dāng)加載此模塊時立即調(diào)用他們
function foo () {
export default 'bar' // SyntaxError
}
foo()
- 命名輸出項
像CommonJS一樣,為了避免給module.exports分配對象,你可以給export定義綁定
下面的代碼塊展示了ES6模塊API的定義.
export var foo = 'bar'
export var baz = 'ponyfoo'
- 綁定,綁定,不是數(shù)值和引用。
下面是文檔對于此特性的定義,
That means that a foo variable you export would be bound into the foo variable on the module, and its value would be subject to changes made to foo. I’d advise against changing the public interface of a module after it has initially loaded, though.
也就是說 export中輸出的屬性,將會和模塊export屬性綁定,當(dāng)輸出的屬性改變時,會影響到模塊的值跟著改變.文檔作者建議,當(dāng)加載某模塊時,盡量不要修改模塊公共接口,以免影響其他同時加載此模塊的代碼段。
export var foo = 'bar'
setTimeout(() => foo = 'baz', 500)
- 輸出列表
var foo = 'ponyfoo'
var bar = 'baz'
export { foo, bar }
可以起一個別名.
export foo as ponyfoo
也可以在輸出列表中 as default
export { foo as default,bar}
import
不多說了上代碼
import {default, map} from 'lodash'
import {default as _, map} from 'lodash'
import _, {map} from 'lodash'
import * as _ from 'lodash' //所有