webpack-dev-server使用方法


記錄下webpack-dev-server的用法.

首先,我們來看看基本的webpack.config.js的寫法

 module.exports = {
        entry: './src/js/index.js',
        output: {
            path: './dist/js',
            filename: 'bundle.js'
        }
    }

配置文件提供一個入口和一個出口,webpack根據這個來進行js的打包和編譯工作。雖然webpack提供了

webpack --watch

的命令來動態監聽文件的改變並實時打包,輸出新bundle.js文件,這樣文件多了之后打包速度會很慢,此外這樣的打包的方式不能做到hot replace,即每次webpack編譯之后,你還需要手動刷新瀏覽器。

webpack-dev-server其中部分功能就能克服上面的2個問題。webpack-dev-server主要是啟動了一個使用express的Http服務器。它的作用主要是用來伺服資源文件。此外這個Http服務器和client使用了websocket通訊協議,原始文件作出改動后,webpack-dev-server會實時的編譯,但是最后的編譯的文件並沒有輸出到目標文件夾,即上面配置的:

output: {
    path: './dist/js',
    filename: 'bundle.js'
}

注意:你啟動webpack-dev-server后,你在目標文件夾中是看不到編譯后的文件的,實時編譯后的文件都保存到了內存當中。因此很多同學使用webpack-dev-server進行開發的時候都看不到編譯后的文件。

下面來結合webpack的文檔和webpack-dev-server里部分源碼來說明下如何使用:

啟動

啟動webpack-dev-server有2種方式:

​ 通過cmd line

​ 通過Node.js API

配置

我主要講解下cmd line的形式,Node.js API形式大家去看下官方文檔。可通過npm script進行啟動。

我的目錄結構是:

app
|__dist
|   |__styles
|   |__js
|       |__bundle.js
|   |__index.html
|__src
|   |__styles
|   |__js
|       |__index.js
|__node_modules
|__package.json
|__webpack.config.js

content-base

設定webpack-dev-server伺服的directory。如果不進行設定的話,默認是在當前目錄下。

webpack-dev-server --content-base ./dist
這個時候還要注意的一點就是在webpack.config.js文件里面,如果配置了output的publicPath這個字段的值的話,在index.html文件里面也應該做出調整。因為webpack-dev-server伺服的文件是相對publicPath這個路徑的。因此,如果你的webpack.config.js配置成這樣的:

module.exports = {
    entry: './src/js/index.js',
    output: {
        path: './dist/js',
        filename: 'bundle.js',
        publicPath: '/assets/'
    }
}

那么,在index.html文件當中引入的路徑也發生相應的變化:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
</head>
<body>
    <script src="assets/bundle.js"></script>
</body>
</html>

如果在webpack.config.js里面沒有配置output的publicPath的話,那么index.html最后引入的文件js文件路徑應該是下面這樣的。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
</head>
<body>
    <script src="bundle.js"></script>
</body>
</html>

Automatic Refresh

webpack-dev-server支持2種自動刷新的方式:

Iframe mode

inline mode

這2種模式配置的方式和訪問的路徑稍微有點區別,最主要的區別還是Iframe mode是在網頁中嵌入了一個iframe,將我們自己的應用注入到這個iframe當中去,因此每次你修改的文件后,都是這個iframe進行了reload。

通過查看webpack-dev-server的源碼,lib路徑下的Server.js文件,第38-48行,分別新建幾個流,這幾個流保存了client文件夾下的相關文件:

// Prepare live html page
var livePage = this.livePage = new StreamCache();
fs.createReadStream(path.join(__dirname, "..", "client", "live.html")).pipe(livePage);

// Prepare the live js file
var liveJs = new StreamCache();
fs.createReadStream(path.join(__dirname, "..", "client", "live.bundle.js")).pipe(liveJs);

// Prepare the inlined js file
var inlinedJs = new StreamCache();
fs.createReadStream(path.join(__dirname, "..", "client", "index.bundle.js")).pipe(inlinedJs);
// Init express server
var app = this.app = new express();

// middleware for serving webpack bundle
this.middleware = webpackDevMiddleware(compiler, options);

app.get("/__webpack_dev_server__/live.bundle.js", function(req, res) {
    res.setHeader("Content-Type", "application/javascript");
    liveJs.pipe(res);
});

app.get("/webpack-dev-server.js", function(req, res) {
    res.setHeader("Content-Type", "application/javascript");
    inlinedJs.pipe(res);
});

app.get("/webpack-dev-server/*", function(req, res) {
    res.setHeader("Content-Type", "text/html");
    this.livePage.pipe(res);
}.bind(this));

當使用Iframe mode時,請求/webpack-dev-server/index.html路徑時,會返回client/index.html文件,這個文件的內容就是:

這個頁面會請求live.bundle.js,其中里面會新建一個Iframe,你的應用就被注入到了這個Iframe當中。同時live.bundle.js中含有socket.io的client代碼,這樣它就能和webpack-dev-server建立的http server進行websocket通訊了。並根據返回的信息完成相應的動作。

而Inline-mode,是webpack-dev-server會在你的webpack.config.js的入口配置文件中再添加一個入口,

module.exports = {
    entry: {
        app: [
            'webpack-dev-server/client?http://localhost:8080/',
            './src/js/index.js'
        ]
    },
    output: {
        path: './dist/js',
        filename: 'bundle.js'
    }
}

這樣就完成了將inlinedJS打包進bundle.js里的功能,同時inlinedJS里面也包含了socket.io的client代碼,可以和webpack-dev-server進行websocket通訊。

當然你也可以直接在你index.html引入這部分代碼:

不過Iframe mode和Inline mode最后達到的效果都是一樣的,都是監聽文件的變化,然后再將編譯后的文件推送到前端,完成頁面的reload的。

Iframe mode

Iframe mode下cmd line不需要添加其他的內容,瀏覽器訪問的路徑是:

localhost:8080/webpack-dev-server/index.html。
這個時候這個頁面的header部分會出現整個reload消息的狀態。當時改變源文件的時候,即可以完成自動編譯打包,頁面自動刷新的功能。

Inline mode

使用inline mode的時候,cmd line需要寫成:

webpack-dev-server --inline --content-base ./dist

這個時候訪問的路徑是:

localhost:8080/index.html

也能完成自動編譯打包,頁面自動刷新的功能。但是沒有的header部分的reload消息的顯示,不過在控制台中會顯示reload的狀態。

Hot Module Replacement

開啟Hot Module Replacement功能,在cmd line里面添加--hot

webpack-dev-server --hot --inline --content-base ./dist

其他配置選項

還有一切其他的配置信息可以查閱官方文檔:

--quiet 控制台中不輸出打包的信息
--compress 開啟gzip壓縮
--progress 顯示打包的進度

還有一切其他的配置信息可以查閱官方文檔:

webpack-dev-server-cli

這是我的package.json的文件:

 {
  "name": "reptile",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --devtool eval-source-map --progress --colors --hot --inline --content-base ./dist",
    "build": "webpack --progress --colors"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.13.2",
    "babel-loader": "^6.2.5",
    "babel-preset-es2015": "^6.13.2",
    "babel-preset-react": "^6.11.1",
    "css-loader": "^0.23.1",
    "react": "^15.3.1",
    "react-dom": "^15.3.1",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.14.1"
  }
}

首先命令行:輸入 npm install 所有依賴。然后輸入npm run dev。在瀏覽器中打開localhost:8080/index.html,然后就可以愉快的開發咯。

本地搭建API Server

如果你在本地還啟動了一個api server,port為3000,這個server主要和你的前端應用進行數據交互。這個時候很顯然會出現跨域的問題,那么這個時候,你前端應用的入口文件應當是用你自己啟動的api server提供的。

var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.send('xxx/xxx/index.html'); //這個地方填寫dist/index.html的路徑
})

此外webpack.config.js:

module.exports = {
    entry: './src/js/index.js',
    output: {
        path: './dist/js',
        filename: 'bundle.js',
        publicPath: 'localhost:8080/dist'
    },
    devServer: {
        '/get': {
            targer: 'localhost:3000',
            secure: false
        }
    }
}

將publicPath字段的內容配置為絕對路徑。同時index.html文件中對js引用的路徑也改為絕對路徑

作者:蘋果小蘿卜
鏈接:https://segmentfault.com/a/1190000006670084
來源:SegmentFault 思否
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM