JS ES6 模塊化開發(fā)入門

作者:辰風沐陽 閱讀:1573 發(fā)布時間:2021-10-10 上次更新:2022-07-31

1. 模塊的基本使用


定義一個js模塊

  1. let title = '辰風沐陽'
  2. let url = 'http://waterflosserreview.com/index/art/279.html'
  3. function show() {
  4. console.log('this is show method')
  5. }
  6. export { title, url, show }

type="module" 表示使用模塊化, ./module/1.js 中的 ./ 不能省略

  1. <script type="module">
  2. import { title, url, show } from "./module/1.js"
  3. console.log(title)
  4. console.log(url)
  5. show()
  6. </script>

2. 模塊延遲解析


因為模塊之間會有依賴關(guān)系,所以系統(tǒng)在處理模塊時會加載全部模塊后才會執(zhí)行模塊

所以模塊化js代碼放在 button 標簽之前,也能找到 button 標簽

  1. <script type="module">
  2. console.log(document.querySelector('button'))
  3. </script>
  4. <button>測試</button>

3. 作用域在模塊中的體現(xiàn)


模塊有自己的獨立作用域,在模塊中定義的變量只能在模塊內(nèi)部使用

在模塊內(nèi)部可以使用全局作用域的變量,但在外部則不能使用模塊內(nèi)部的變量,只有使用 export 導出才能在外部使用

4. 模塊的預解析


無論模塊加載多少次,只會在第一次時產(chǎn)生執(zhí)行

5. 模塊的具名導出和導入


具名導出: 顧名思義,就是導出具有名稱的成員

  1. let site = 'wwaterflosserreview.com'
  2. function show() {
  3. console.log('this is show ')
  4. }
  5. export { site, show }

6. 批量導入 * as name


  1. // 導出的內(nèi)容
  2. export { site, url }
  3. // 導入
  4. import * as api from './modules/http.js'
  5. console.log(api.url)
  6. console.log(api.site)

7. 導出、導入 別名的使用


  1. import { site as name } from './modules/user.js'

8. 模塊的默認導出


export 導出數(shù)據(jù)時使用 default 代表時默認導出,那么在導入模塊時接收的名稱可以任意定義

  1. export default function show() {
  2. console.log('this is show ')
  3. }
  4. import api from './modules/show.js'

默認導出本質(zhì)上是給導出的成員設(shè)置了別名 default,這也是默認導出只能寫一個的原因

  1. export { show as default }

接收默認導出的成員,下面兩種寫法都可以

  1. import user from './modules/show.js';
  2. import { default as user } from './modules/show.js';

具名導出和默認導出的混合使用及其導入

  1. // 導出
  2. export const domain = 'http://waterflosserreview.com';
  3. export default function request() {
  4. return new Promise((resolve, reject) => { });
  5. }
  6. // 導入
  7. import request, { domain as url } from './modules/request.js';

9. 模塊的合并導出


創(chuàng)建一個模塊(merge.js)進行合并導出

  1. import * as user from './modules/user.js';
  2. import * as admin from './modules/admin.js';
  3. export { user, admin }

導入合并后的模塊

  1. import * as api from './modules/merge.js';
  2. // 訪問方式
  3. // api.user.成員
  4. // api.admin.成員

視頻推薦


后盾人向軍: JS模塊化開發(fā),編寫高可用代碼

標簽: JavaScript