# ES模組,匯出與匯入 (5) ###### tags: `JavaScript` 2022.2.28 ## 介紹 &emsp;&emsp;在`<script type="module">`添加模組程式即可使用,當程式需要引用其他檔案的方法時,可採用以下三種形式: ### 1. 預設匯出 &emsp;&emsp;預設匯出旨沒有給定特定名稱方法或資料,再引入時需要再額外命名,Vue最常運用到。 * 引入檔案「export1.js」 ``` export default { data: [ // 資料 '這是第一句話', '這是第二句話', '這是第三句話', ], render(dom) { // 渲染方法 const list = document.querySelector(`${dom} ul`); let content = ''; this.data.forEach((item, i) => { content = `${content}<li>${item} <button type="button" class="btn" data-id="${i}">移除</button></li>`; }); // 縮寫優化 // const content = component.data.map(item => `<li>${item}</li>`).join(''); console.log(this.data) list.innerHTML = content; // 加入監聽 const btns = document.querySelectorAll(`${dom} .btn`); btns.forEach((btn) => btn.addEventListener('click', (e) => { // #2 重點,移除項目是先移除資料,而不是直接移除 DOM // 如果要進行 AJAX 或更複雜行為,不會因為 DOM 與資料混合而難以運作 const id = e.target.dataset.id; this.data.splice(id, 1); this.render(dom); }) ); }, }; ``` * 如何引入寫法 ``` import newCompomemt from './export1.js'; newCompomemt.init(); ``` ### 2. 具名匯出 &emsp;&emsp;旨在匯出時有指定名稱,通常用於匯出方法用。 * 引入檔案「export2.js」 ``` export const a = 1; export b(){ console.log(1); } export c(a=1,b=2){ console.log(a+b); } ``` * 如何引入寫法 ``` 1.單一匯入 (建議寫法) import {a,b,c} from './export2.js' console.log(a,b(),c(1,2)); 2.全部匯入(不建議,錯誤較難發現) import * as all from './export2.js' console.log(all.a,all.b(),all.c(1,2)); ``` ### 3. SideEffect &emsp;&emsp;屬於早期寫法,現在較少使用 * 引入檔案「export3.js」 ``` (function(global){ global.$ = '我是 JQuer;'; })(window); ``` * 如何引入寫法 ``` import './export3.js' console.log($); ```