【轉】webpack使用方法(二):執行webpack
阿新 • • 發佈:2022-05-07
原文:https://blog.csdn.net/simpleasong/article/details/123017040
我們通過一個示例來執行webpack,結構如下:
-
在根目錄下新建setup資料夾,在setup資料夾中新建src資料夾。
-
在src下新建helloWorld.js,寫一個函式,通過export default預設匯出printStr方法。
// helloWorld.js function printStr() { console.log("hello world!"); } export default printStr;
-
在src下新建index.js,通過模組匯入的方法,來匯入printStr方法。
// index.js import printStr from "./helloWorld.js"; printStr();
-
在根目錄安裝一下webpack和webpack-cli。
-
安裝成功後在setup資料夾上點選滑鼠右鍵,選擇“在整合終端中開啟”,執行命令
webpack
此時會報一個錯誤
這是由於我們將webpack和webpack-cli安裝到了根目錄,所以當前目錄無法識別webpack指令。 -
此時可以執行npx webpack命令,npx依託於npm,它的作用就是觀察在當前目錄下有沒有你想執行的命令,沒有就會去上一級目錄尋找。
npx webpack
打包完成
並且在setup目錄下生成了一個dist資料夾,裡面有一個main.js檔案。 -
此時打包工作已經完成了,可以在setup資料夾下新建一個index.html,引入打包後生成的main.js看看效果
-
在瀏覽器上開啟index.html頁面,可以看到"hello world"被打印出來了。