# ES module 模組化|筆記 by Jiang ###### tags: `Jiang` `Vue新手夏令營` - [Vue 新手夏令營 課程頁面](https://hackmd.io/@dbFY0UD9SUeKmNXhWf01ew/BkJoW-hn_/%2FC05go-8iTSS-nrMwKU22kA) - [:sun_with_face:筆記入口](/2JiZbCPdR0G4p5fNycPmTg) ## 這裡開寫囉 ```jsx <script type="module"> // JS模組化,將檔案拆分,匯入匯出 // #1 匯出匯入本一體,先掌握匯出更容易理解匯入 // #1-1 將標籤定義 <script type="module"> 加入這段程式碼才能匯出匯入 // #1-2 預設匯出:defaultExport.js 每個檔案唯一 本身沒有名稱要自訂名稱 import 自訂名稱 from... // 常見的匯出方式,通常用於匯出物件,在 Vue 開發中可用來匯出元件 export default { ... } // #1-3 具名匯出:namedExport.js 每個檔案多個 本身有名稱 用大括號包名稱 import {具名名稱 } from... // 可用於匯出已定義的變數、物件、函式,專案開發中通常用於 “方法匯出” 較常用在函式的匯出 // 第三方的框架、函式、套件很常使用具名定義 “方法” export const a = 1; export function b() { console.log('1'); } export function c(a, b) { return a + b; } // #2 匯入方法 // #2-1 預設匯入 // 因為預設匯出沒有名字,所以可以為它命名 import newComponent from './export1.js'; newComponent.init(); // 注意:因為傳參考的特性,因此元件無法重複利用(Vue.js 中會解決此問題) // #2-2 具名匯入 // 單一匯入(建議寫法) import { a,b } from './export2.js' console.log(a); b(); // 全部匯入(不建議,錯誤較難發現) import * as all from './export2.js'; console.log(all.a); all.b(); console.log(all.c(1,2)); // #3 SideEffect // sideEffect.js(沒有包含匯出的檔案) import './sideEffect.js'; console.log($); // 可直接進行匯入 (function (global) { global.$ = '我是 jQuery'; })(window); </script> ``` ```jsx <script type="module"> // #1 每一個 type="module" 的作用域都是獨立的 var a = 1; window.b = 2; </script> <script > console.log(b); </script> <div id="app">{{ counter }}</div> <script type="module"> // #2 可以運用的 ESM 套件 // 網路上找到的 “ESM”,如果條件允許是可以使用 import 方式載入 // https://cdnjs.com/libraries/vue // 比對語法:https://v3.vuejs.org/guide/introduction.html#declarative-rendering import {} from 'https://cdnjs.cloudflare.com/ajax/libs/vue/3.1.4/vue.esm-browser.min.js' const Counter = { data() { return { counter: 0 } } } Vue.createApp(Counter).mount('#app') </script> ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up