iT邦幫忙

0

JavaScript 模組化:具名、預設與全部匯出詳解

  • 分享至 

  • xImage
  •  

具名匯出 (Named Exports)

  • 通常用於封裝方法
  • 需要先宣告才能匯出

test.js 內容:

export const a = 1;

export function fn() {
  console.log('123');
}

index.html內容:

import { a, fn } from "./test.js";

fn(); // 輸出: 123
console.log(a); // 輸出: 1

預設匯出 (Default Exports)

  • 在框架中,通常作為元件 (Component) 使用
  • 每個檔案只能有一個預設匯出

test.js 內容:

export default {
  myName: '小明',
  callSomeone() {
    console.log(this.myName);
  }
};

index.html內容:

// import 賦予名稱 from 路徑
import Ming from "./test.js";
      
Ming.callSomeone();

全部匯出

  • 將模組中的所有匯出(包含具名匯出和預設匯出)匯入到一個命名空間物件中

test.js 內容 (假設同時包含具名匯出和預設匯出):

export const b = 2;

export function greet(name) {
  console.log(`Hello, ${name}!`);
}

const defaultExport = {
  message: '這是預設訊息'
};

export default defaultExport;

index.html內容:

// 全部匯入
import * as all from "./test.js";

console.log(all.b); // 輸出: 2
all.greet('杰倫'); // 輸出: Hello, 杰倫!
console.log(all.default.message); // 輸出: 這是預設訊息

圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言