webpack-dev-server啓動了一個使用express的Http服務器,這個服務器與客戶端採用websocket通訊協議,當原始文件發生改變,webpack-dev-server會實時編譯。css
這裏注意兩點:html
1.webpack-dev-server伺服的是資源文件,不會對index.html的修改作出反應vue
2.webpack-dev-server生成的文件在內存中,所以不會呈現於目錄中,生成路徑由content-base指定,不會輸出到output目錄中。react
3.默認狀況下: webpack-dev-server會在content-base路徑下尋找index.html做爲首頁webpack
4.webpack-dev-server不是一個插件,而是一個web服務器,因此不要想固然地將其引入web
content-base 用於設定生成的文件所在目錄express
eg:sass
const path = require('path'); const HtmlWebpackPlugin= require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin') var ManifestPlugin = require('webpack-manifest-plugin'); const webpack= require('webpack'); module.exports = { entry: { main: './src/main.js' }, devServer: { historyApiFallback: true, noInfo: true, contentBase: './dist' }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] },{ test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } },{ test: /\.vue$/, loader: 'vue-loader', options: { loaders: { 'scss': 'vue-style-loader!css-loader!sass-loader', 'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax', } } } ] }, devtool: 'inline-source-map', output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') }, };
這裏設定在dist文件夾下生成文件,可以看到dist文件夾下未生成文件(index.html是本人手動建立的),而index.html的引入路徑應爲<script src="./main.js"></script>服務器
必須注意的是: 若是配置了output的publicPath這個字段的值的話,index.html的路徑也得作出相應修改,由於webpack-dev-server伺服的文件時相對於publicPath這個路徑的。websocket
那麼,若是:
output: { filename: '[name].js', path: path.resolve(__dirname, 'dist'), publicPath: '/a/' }
那麼,index.html的路徑爲: <script src="./a/main.js">
內聯模式(inline mode)和iframe模式
webpack-dev-server默認採用內聯模式,iframe模式與內聯模式最大的區別是它的原理是在網頁中嵌入一個iframe,
咱們能夠將devServer的inline設爲false切換爲iframe模式
devServer: { historyApiFallback: true, noInfo: true, contentBase: './dist', inline: false }
能夠發現:
能夠發現咱們的網頁被嵌入iframe中。
模塊熱替換
webpack-dev-server有兩種方式開啓熱替換
1.經過在devServer內將hot設爲true並初始化webpack.HotModuleReplacementPlugin
2.命令行加入--hot(若是webpack或者webpack-dev-server開啓時追加了--hot, 上述插件能自動初始化,這樣就無需加入配置文件中)
而後在入口文件中加入熱替換處理代碼:
if (module.hot) {
//當chunk1.js發生改變時熱替換 module.hot.accept('./chunk1.js', function() { console.log('chunk1更新啦'); }) }
默認狀況下,因爲style-loader的幫助,css的模板熱替換很簡單,當發生改變時,style-loader會在後臺使用module.hot.accept來修補style,同理,有許多loader有相似功能,例如vue-loader、react-hot-loader...
而js文件發生改變會觸發刷新而不是熱替換,所以得加上處理語句,詳情可查看:
https://doc.webpack-china.org/guides/hot-module-replacement