iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0
JavaScript

歡迎參加我的原生JS畢業典禮系列 第 9

【Day8】模組化概念—ES6 Modules

  • 分享至 

  • xImage
  •  

「阿這個功能我不是昨天才寫過嗎?是在哪個頁面寫的?」隨著開發專案逐漸龐大,不可能單靠複製貼上來重複撰寫。把龐大的代碼細化成小模組,讓彼此各司其職,就是今天要來學的模組化概念!

但在開始之前…

Modules跟Components差在哪?

兩者間都有「拆分」、「組合」的概念,差別在於切入點的不同(哇!還是好抽象)
◎假設我們要參加「教室布置比賽」主題是「動物園」,要把同學們劃分成不同的小組進行分工:

  • Modules:我們依據製作流程分組
    1.採購組—買齊所有的製作材料
    2.剪紙組—依照需求把圖案剪成各種大小
    3.黏貼組—把素材都黏在對應的位置上
  • Components:我們依據動物園素材(UI)分組
    1.老虎組
    2.斑馬組
    3.草地組

模組化(Modules)是透過程式邏輯進行拆分;而元件、組件(Components)則是以UI為出發點進行規劃。

ES6是什麼?

ES是ECMAScript的縮寫,它是JS的標準規格,在2015年發布了第6版本,大家也稱之為ES6。而這個版本是JS歷史上的重大更新,推出了許多實用的新特性:廣為人知的箭頭函式、Promise的出現解救了callback hell…等,詳見:ES6(ES2015)有什麼新特性?

也是在ES6中,JS終於推出了官方模組化:

import / export

在原生JS中要載入ES Module,必須在標籤上加上<script type="module">;Vue3使用了import/export相關語法,因此我們可直接輸入!以下介紹兩種export搭配import使用方法:

1.named export 具名匯出&import

1-1.只要在參數、函式前面加上export就可以使用:

//hello.js
export const lastName = "Ivy";
export function printing() {
    console.log(lastName);
}

1-2.也可以把要匯出的內容用{}包起來:

//hello.js
const lastName = "Ivy";
function printing() {
    console.log(lastName);
}
export { lastName,printing } //也可以把要匯出的內容用{}包起來,{}不可省略

1-3.在{}中更改名稱後匯出:

//hello.js
...
export { lastName as newName,printing as writing};

1-4.import也可以更名匯入:

//1-1
import { lastName } from "./hello.js";
//1-2
import { lastName,printing } from "./hello.js";
//1-3
import { newName as name,writing } from "./hello.js"; //要使用export更名後的名稱

2.default export 預設匯出&import

每個輸出模組JS中只會有一個default export,因此:
2-1.匯出時不需要具名:

//hello.js
export default "Ivy";

2-2.匯出目標只有一項,可以不使用{}

//hello.js
const name = "Ivy";
export default name;

2-3.import可以命名,且一樣不需使用{}

//2-1
import firstName from "./hello.js";
//2-2
import name from "./hello.js";

3.import / export 物件形式

named export情況下,匯出好多內容;import端可以使用*萬用字元把他們組成一個物件調用:

import * as module from "hello.js";
console.log(module.lastName); //"Ivy"

default export則是普遍用來匯出一包物件:

//hello.js
export default {
    lastName:"Ivy",
    firstName:"Tien",
    hello:function() {
        console.log("hello!");
    },
}
import module from "hello.js";
console.log(module.hello()); //"hello!"

小結

理解模組化的概念感覺離效率開發又更近了一步,後續我們再來看看Vue提供了什麼資源讓我們能夠模組化管理!


參考資料
vue中組件化和模組化有什麼區別
JavaScript - 為什麼 ES6 總是特別拿出來提?
JavaScript ES6 Modules 模組系統
模組化 (1) - Export / Import


上一篇
【Day7】輔修CSS預處理器—在Vue專案加入Sass/SCSS
下一篇
【Day9】組件化概念—Vue Components註冊與使用
系列文
歡迎參加我的原生JS畢業典禮12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言