跳到主內容

【ES6】ESModual

image-1674749911584.png

什麼樣的匯出對應什麼樣的匯入

預設匯入(一個匯出檔只能有一個)

常見的匯出方式,通常用於匯出物件,在 React 開發中可用來匯出元件
/** 匯出頁 exportDefault.js */
export default function fn(){
	console.log("default export")
}

/** 匯入 index.html */
/** export ${name}(隨便取) from ${path} */
<script type="module">
	export aa from "./exportDefault.js";
	aa();
</script>
/** 匯出頁 exportDefault.js */
export default {
	name: "sam",
    func: function(){
    	console.log("預設方法...")
    }
}

/** 匯入 index.html */
/** import ${name}(隨便取) from ${path} */
<script type="module">
	import aa from "./exportDefault.js";
	console.log(aa.name);
    aa.func();
</script>

具名匯入(可多個)

可用於匯出已定義的變數、物件、函式,專案開發中通常用於 “方法匯出”
第三方的框架、函式、套件很常使用具名定義 “方法
/** 匯出頁 exportModule.js */
export const myName = "Jhon"
export function fn1() {
	console.log("function 1");
}

/** 匯入 index.html */
/** import { 解構名稱 } from ${path} */
<script type="module">
	import {fn1, myName} from "./exportDefault.js";
    console.log("myName",myName);
	fn1();
</script>

全部匯出(不常用)

/** 匯出頁 exportModule.js */
export const myName = "Jhon"
export function fn1() {
	console.log("function 1");
}

/** 匯入 index.html */
/** import * as ${別名} from ${path} */
<script type="module">
	import * as bb from "./exportDefault.js";
    console.log("myName",bb.myName);
	bb.fn1();
</script>

sideEffect (舊函式庫,立即執行)

/** 匯出頁 sideEffect.js */
(function(global){
	global.$ = "I am jquery";
})(window)

/** 匯入 index.html */
/** import ${path} */
<script type="module">
	import "./sideEffect.js";
    console.log("$",$); // I am jquery
	bb.fn1();
</script>