webpack-dev-server啟動了一個使用express的Http服務器,這個服務器與客戶端采用websocket通信協議,當原始文件發生改變,webpack-dev-server會實時編譯。
這里注意兩點:
1.webpack-dev-server伺服的是資源文件,不會對index.html的修改做出反應
2.webpack-dev-server生成的文件在內存中,因此不會呈現於目錄中,生成路徑由content-base指定,不會輸出到output目錄中。
3.默認情況下: webpack-dev-server會在content-base路徑下尋找index.html作為首頁
4.webpack-dev-server不是一個插件,而是一個web服務器,所以不要想當然地將其引入
content-base 用於設定生成的文件所在目錄
eg:
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這個路徑的。
那么,如果:
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