ES20XX Modern JS 新語言特性筆記 | Modules (ES6 Modules)


  1. 說明
    1. Export
      1. Default Export
      2. Named Export
      3. Partial Export
    2. Import
      1. Import Default
      2. Import Named
      3. Import Without binding
      4. Import as Const
  2. 參考資料
    1. ES20XX
    2. Node.js Dancing with ES20XX

筆記從 ES2015 / ES2016 / ES2017 / ES2018 / ES2019 / ES2020 以來,JS 所加入的新語言特性。使用的情境新語言特性不僅是為了減少對第三方套件的依賴 (Lodash),也是基於 ESLint 上 Clean Code、Best Practices 規範要求。熟悉新語言特性不僅能夠使 JS 開發更加快速也能夠提升閱讀性。

JavaScript logo

說明

想要先談的幾個新語言特性,都是被 ESLint 糾正或者是開發過程中恰好需要的。本篇筆記為 Modern ES6 Modules。

在 Vue.js 專案當中,使用 Vue Components 的設計方式或者使用第三方的元件,都會使用到 Moduels,曾經好幾個小時就是為了處理 firebase 的載入 bug ,而當時如果能夠有更清晰的對於 Modules 的認識,能夠讓除錯的時間大幅提升。

Export

Default Export

每個 JS file 只能有一個 default export,提供 import 不指定使用對象的時候作為預設使用。此外也可以不提供 default export。

const Loto = {
    hp: 15,
    str: 3,
    vit: 2,
}

export default Loto;

此外也可以下列各種方式使用 default export,但再次提醒每個 JS file 只能有一個 default export。

export default 42;
export default () => { return 'hello' };

Named Export

與 default export 相對的則是 named export,named export 不限定在 JS file 的輸出數量,但必須為每個 export 的對象提供一個名稱。

// export named variable
export let greeting = 'foobar';

function foo() {
    console.log('foo');
}

const bar = 1024;

// multiple named export
export {bar, foo}

Named export 時可以使用 as 改變提供外界使用的對象名稱:

export {bar as rab}

Export 的對象都需要有一個名稱,如果要 export arrow function 可以使用下列方式:

export const af = () => "I'm arrow function"

Partial Export

function ham(){
  return 'ham, egg, spam';
}

function egg(){
  return ham();
}

// export partial is work
export {egg}

Import

除瀏覽器必須支援外,在 html 當中的宣告必須要加入 type 指名為 module,才能夠正確地進行模組的使用。

<script type="module" src="app.js"></script>

Import Default

mod.js

const Loto = {
    hp: 15,
    str: 3,
    vit: 2,
}

export default Loto;

app.js

import loto from './mod.js';                 // import the default export of a module
console.log(loto.hp, loto.str)

Import Named

mod.js

function foo() {
    console.log('foo');
}

const bar = 1024;

// multiple named export
export {bar, foo}

app.js

import { foo, bar } from './app.js';
// allowed: foo = function, bar = 1024
import { foo as oof } from './app.js';
// allowed: oof = function
import * as $ from './app.js';
// allowed: $.foo, $.bar

Import Without binding

如果不需要 Import 相關變數、函式來使用,只是要使用其他模組 Global 的行為,例如對於 BOM 或 DOM 的操作時,可以使用這樣的引入方式。

mod.js

window.addEventListener(
  "load",
  function() { document.body.style.background = 'ivory'; }
);

app.js

import './mod.js'

Import as Const

Import 來的變數、函式,儘管當初是宣告為 let 或是 var,離開原本的 JS file 後,在引入的地方都會被視為 const 對代,因此無法進行修改。如果要變更引用來源的資料,必須要由來源提供對應的函式(類似 Setter 介面)的方式來進行修改、異動。

參考資料

模組系統 | 從ES6開始的JavaScript學習生活

JavaScript Tutorial

ES20XX

JavaScript: What’s new in ECMAScript 2019 (ES2019)/ES10?

ES2020 中 Javascript 10 個你應該知道的新功能

Node.js Dancing with ES20XX

查詢 Node.js 各版本對於 Ecma JavaScript 的支援情況。目前主要使用的 Node.js 12.10 對於 ES2019 以前都有相當高的支援情況,所以使用新 Feature 無煩惱。

Node.green