JavaScript 匯入和匯出模組


要使用 JavaScript 匯入和匯出模組,程式碼如下 −

說明 − 要執行此示例,您需要執行一個 localhost 伺服器。

INDEX.html

示例

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Importing and Exporting Modules</h1>
<button class="Btn">IMPORT</button>
<div class="result"></div>
<h3>
Click on the above button to import module
</h3>
<script src="script.js" type="module"></script>
<script src="sample.js" type="module"></script>
</body>
</html>

script.js

import test from './sample.js';
document.querySelector('.Btn').addEventListener('click',()=>{
   test();
})

sample.js

let resultEle = document.querySelector(".result");
export default function testImport(){
   resultEle.innerHTML = 'Module testImport has been imported';
}

輸出

單擊“IMPORT”按鈕後,顯示 −

更新於: 12-May-2020

215 次瀏覽

開啟你的 職業生涯

透過完成本課程獲得認證

開始學習
廣告
© . All rights reserved.