JavaScript 中的模塊如何打包運行(四)
選項 3: module-src-export-import 法
這是選項 2 的一個變種,將 index.html 中 < script type="module"> ... </script> 之間的 JavaScript 代碼移到 index.js 中。然后,在 index.html 中,包含 index.js。
? ? < script type="module" src="index.js"></script>
注意:不要忘記了 type="module" 。


選項 4: webpack-bunlde-src 法
將所有的 JavaScript 文件打包成一個 JavaScript 文件使用。
- 創(chuàng)建一個目錄 src, 將 index.js 與 change.js 移入。
- 執(zhí)行 npm init -y,此時會生成 package.json。
- 執(zhí)行 npx webpack, 此時會新增一個 dist 目錄,里面包含 main.js。這個 main.js 就是 webpack 將 index.js 與 change.js 打包(bundle)在一起,然后最小化的 JavaScript 文件,可以直接包含進來用??梢园l(fā)現(xiàn),main.js 文件小于 index.js 與 change.js 文件大小之和,可見 webpack 做了最小化。
- 將 index.html 移入 dist 目錄,將 < script type="module" src="index.js"></script> 修改為 < script src="main.js"></script>。 打開 index.html, 顯示正確結(jié)果。

目錄樹結(jié)構(gòu):
? ? package.json
? ? src/
? ? ? - index.js
? ? ? - change.js
? ? dist/
? ? ? - main.js
? ? ? - index.html