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.