ES6 Modules 各種寫法的範例展示

 

準備 animal.js、default.js、itself.js、entry.js、index.html 範例,

index.html 會引入 entry.js,而 entry.js 分別會引入 animal.js、default.js、itself.js 模組做範例展示。

 

animal.js

export function cat() {
    console.log("I'm cat");
}

export function dog() {
    console.log("I'm dog");
}

 

default.js

export function func() {
    console.log("the default");
}
export default func;

/**equal to below approach one*/
//function func() {
//    console.log("the default");
//}
//export default func;

/**equal to below approach two*/
// export default function func() {
//     console.log("the default");
// }

 

itself.js

/**import this file into itself */
import * as rename from "./itself.js";
rename.func();

export default func;
export function func() {
    console.log("the itself");
}

 

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
</head>

<body>
    <script src="entry.js" type="module"></script>
</body>

</html>

注意,現階段 script tag 的屬性要特別標示 type="module",才能正常動作。

 

entry.js

/**named export */
import { cat, dog } from "./animal.js";
cat();
dog();

/**Namespace Imports */
import * as alies from "./animal.js";
alies.cat();
alies.dog();

/**Aliasing named imports */
import { cat as reNameCat, dog as reNameDog } from "./animal.js";
reNameCat();
reNameDog();

/**The Default Export as the API */
import func from "./default.js";
func();

/**import this file into itself */
import * as arbitrary from "./itself.js";
//import "./itself.js";

注意,要在 hosted 的環境下使用

 

執行結果為

 

參考資料:

import

ES Modules: Using Named Exports as the Default Export

ECMAScript 6 — New Features: Overview & Comparison

Module 的语法

彻底搞清楚javascript中的require、import和export