webpack教程02-webpack-dev-server是什麼與webpack-dev-server命令行使用

本文首發於我的Github博客

本文是webpack教程的第二篇文章,會介紹:

  • webpack-dev-server的概念和作用
  • webpack-dev-server的基本命令行使用和一個坑點

本次相關代碼在Github倉庫 commit bbaea1bc

webpack-dev-server的概念與作用

概念

webpack-dev-server,顧名思義,這是一個server,也就是說,webpack-dev-server命令能夠用來啓動一個本地服務器,接受HTTP請求

作用

不使用webpack-dev-server的場景

在上一次的教程中,我們是採用直接打開index.html文件的方式來查看我們web app的實現效果

但是,這樣的話我們的瀏覽器地址欄中會是file://path/to/index.html

也就是說,使用的協議是文件協議,並不會發起HTTP請求,只會從本地文件系統將文件加載到瀏覽器裏

這樣的話,我們就無法使用很多HTTP協議特性,無法使用也就無法測試,調試,對開發工作有很大的阻礙

使用webpack-dev-server

通過webpack-dev-server,我們能夠直接啓動一個簡易的服務器,通過這個服務器,可以使用HTTP協議進行web app的效果測試

除此之外,還能夠實現許多額外的功能,比如熱加載(一旦修改項目文件,就自動重新加載服務器)

webpack-dev-server的基本命令行使用和一個坑點

基本命令行使用

想要從webpack轉向webpack-dev-server是比較簡單的,因爲webpack-dev-server兼容了webpack所有的命令行選項

這也是很合理的,因爲webpack-dev-server基本上就是"webpack打包 + 啓動簡易服務器"

所以我嘗試直接將npm配置中的webpack命令修改爲webpack-dev-server命令

    "build": "webpack-dev-server ./js/app.js -o bundle.js --mode development"

而後npm run build

> npm run build
 「wds」: Project is running at http://localhost:8081/
 「wds」: webpack output is served from /
 「wds」: Content not from webpack is served from /path/to/working-dir

打開localhost:8081,發現代碼運行正常,且瀏覽器使用的是HTTP協議

一個坑點

坑點總結

  1. webpack-dev-server不會在文件系統中生成打包後的文件,而是直接將文件加載到內存裏
  2. 對於打包後的文件,默認會放置在host的/路徑下,需要配置publicPath來自定義host路徑

過程

但是,當我希望將生成的bundle.js放入固定文件夾dist時,問題出現了

npm配置

    "build": "webpack-dev-server ./js/app.js -o ./dist/bundle.js --mode development"

HTML文件

<body>
<!-- .... -->
<script src="dist/bundle.js"></script>
</body>

但是在打開localhost:8081之後,代碼運行異常(按鈕不起作用),console報錯

GET http://localhost:8081/dist/bundle.js net::ERR_ABORTED 404 (Not Found)

這說明dist/bundle.js沒有能被加載,且磁盤上沒有dist/bundle.js文件生成

查看npm run build的日誌輸出

> npm run build
ℹ 「wds」: Project is running at http://localhost:8081/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from

其中

ℹ 「wds」: webpack output is served from /

這一行比較引人注意,因爲dist/bundle.js正是webpack output

於是我訪問了localhost:8081/bundle.js,發現可以正常訪問

於是去webpack的官網文檔中尋找解決方案,在這個文檔上找到了這麼一個提示

webpack-dev-server doesn’t write any output files after compiling. Instead, it keeps bundle files in memory and serves them as if they were real files mounted at the server’s root path. If your page expects to find the bundle files on a different path, you can change this with the publicPath option in the dev server’s configuration.

對於配置文件,我們需要指定publicPath

對於webpack-dev-server CLI,我們需要指定output-public-path,所以將npm配置修改爲

    "build": "webpack-dev-server ./js/app.js -o ./dist/bundle.js --output-public-path /dist/  --mode development"

代碼運行就可以恢復正常,localhost:8081/dist/bundle.js也可以正常訪問

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章