Webpack html插件優化、devServer、熱更新(二)

一、clean-webpack-plugin:

在每次生成dist目錄前,先刪除本地的dist文件(每次自動刪除太麻煩)

2、安裝clean-webpack-plugin   npm/cnpm i clean-webpack-plugin --save -dev

3、在我們的webpack.config.js文件中引入

    const  cleanWebpackPlugin=require('clean-webpack-plugin');

    然後在plugs中進行配置

        plugins:[

            new CleanWebpackPlugin(['dist']), //傳入數組,指定要刪除的目錄

        ]

二、HotModuleReplacementPlugin

啓用熱替換模塊(Hot Module Replacement),也被稱爲 HMR。

W永遠不要在生產環境(production)下啓用 HMR

基本用法(Basic Usage)

啓用 HMR 非常簡單,在大多數情況下也不需要設置選項。

new webpack.HotModuleReplacementPlugin({
  // Options...
})

選項(Options)

包含如下選項:

  • multiStep (boolean):設置爲 true 時,插件會分成兩步構建文件。首先編譯熱加載 chunks,之後再編譯剩餘的通常的資源。
  • fullBuildTimeout (number):當 multiStep 啓用時,表示兩步構建之間的延時。
  • requestTimeout (number):下載 manifest 的延時(webpack 3.0.0 後的版本支持)。

W> 這些選項屬於實驗性內容,因此以後可能會被棄用。就如同上文所說的那樣,這些選項通常情況下都是沒有必要設置的,僅僅是設置一下 new webpack.HotModuleReplacementPlugin() 在大部分情況下就足夠了。





webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const Webpack = require('webpack');//1熱更新
module.exports = {
// entry:['./src/index.js','./src/index2.js'],
entry:{
index:'./src/index.js',
index2:'./src/index2.js'
},
output:{
path:path.resolve(__dirname,'dist'),
filename:'[name].boundle.js'
},

        
//devServer
devServer:{
//設置服務器訪問的基本目錄
contentBase:path.resolve(__dirname,'dist'),
//服務器ip地址,localhost
host:'localhost',
port:8090,
open:true,//自動打開瀏覽器
hot:true//2熱更新
},


plugins:[
new Webpack.HotModuleReplacementPlugin(),//3熱更新
new CleanWebpackPlugin(['dist']),//刪除dist
new HtmlWebpackPlugin({
minify:{
collapseWhitespace:true,//壓縮空白
removeAttributeQuotes:true//刪除屬性雙引號
},
hash:true,//消除緩存,添加版本號
template: './src/index.html',//模板地址
title: ' Webpack4.x ',
filename: 'index.html',//生成多個頁面
chunks:['index']//多頁面分別引入自己的js
}),
new HtmlWebpackPlugin({
hash:true,
template:'./src/index2.html',
title: '第二個頁面',
filename:'index2.html',
chunks:['index2']
})
]


}

參考webpack中文文檔:http://www.css88.com/doc/webpack2/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章