const config = { "author": "glpla", "desc": "only for test", "url": "glpla.github.io", "version": "1.0.0", } const greeting = (name) => { console.log(`output->name`, name) } export { config, greeting }
<script type="module"> import {config} './test.js' console.log(config.author) </script>
<script type="module"> import * as obj from './test.js' console.log(obj.config); console.log(obj.greeting); </script>
export default (name) => { console.log(`${name}, hi, there.`) }
<script type="module"> import sayHi from './test.js' sayHi('glpla') </script>
let x = 10 function add() { return x + 10 } let y = 20 function time() { return y * 10 } add() time()
文件 modAdd.js
export default function () { const dom = document.querySelector('#add') const x = 10 function add() { dom.innerHTML = Number(dom.textContent) + x } return { x, add } }
文件 modTime.js
export default function () { const dom = document.querySelector('#time') const y = 10 function time() { dom.innerHTML = Number(dom.textContent) * y } return { y, time } }
文件 app.js - 引入并使用模块;需要指定 <script> 类型 type 为 module
<script type="module"> import modAdd from './modAdd.js' import modTime from './modTime.js' let addBtn = document.querySelector('#add') let timeBtn = document.querySelector('#time') const { x, add } = modAdd() const { y, time } = modTime() addBtn.addEventListener('click', add) timeBtn.addEventListener('click', time) </script>