首頁  >  文章  >  web前端  >  詳解ES6模組化和CommonJS模組化的區別

詳解ES6模組化和CommonJS模組化的區別

青灯夜游
青灯夜游轉載
2020-06-22 18:23:092375瀏覽

詳解ES6模組化和CommonJS模組化的區別

ES6 模組化與CommonJS 模組化區別

在最近的專案中關於ES6 的import、export 和CommonJS 中的module.exports、require 的使用傻傻搞不清楚,今天下定決心總結一下,有什麼不對的地方,還請諸位多多指教。

ES6 模組化

#import指令用於輸入其他模組提供的功能;export指令用於規定模組的對外介面。

一、 import  與export

// 导出 a.js

/** 写法一 **/
var name = 'sheep'
function getSheep() {
    name = 'hourse'
}
export {getSheep}

// 引入 b.js
import {getSheep} from './a.js'


/** 写法二 **/
var name = 'sheep'
export function getSheep() {
    name = 'hourse'
}

// 引入 b.js

import {getSheep} from './a.js'

二、 import  與export defalut

#export 可以有多個,export default只有一個

// 导出 a.js
let obj = {
    name: 'hello',
    getName: function (){
        return this.name
    }

export default obj

// 引入 b.js

import obj from './a.js'

CommonJS 模組化

一、 require  與module.exports

#require 在ES6(bable將import轉換為require) 和CommonJS 都支援

// 导出 a.js

let obj = {
    name: 'hello',
    getName: function (){
        return this.name
    }

module.exports = obj

// 引入 b.js

let obj = require('./a.js')

總結

  • ##即使我們使用了ES6 的模組系統,如果借助Babel 的轉換,ES6 的模組系統最終還是會轉換成CommonJS 的規範。
  • Babel5 中使用 require 時,引入值是 module.export 傳回的值或是 export default 傳回的值。

Babel6中,使用import 引入時,可以直接取得到export default 的值; 但是如果是require 導入的元件, 無論匯出是module.export 、export 、 export default可以直接取得到export default 的值都必須加上一個default。

#########參考文獻:############https://www.jianshu.com/p/27ee06296bcd######## #####https://juejin.im/post/5a2e5f0851882575d42f5609###############推薦教學:《###JS教程###》###

以上是詳解ES6模組化和CommonJS模組化的區別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除