Webpack 多html入口、devServer、热更新配置

在每次生成dist目录前,先删除本地的dist文件(每次自动删除太麻烦)

1、安装clean-webpack-plugin npm/cnpm i clean-webpack-plugin --save -dev

2、在我们的webpack.config.js文件中引入

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

然后在plugs中进行配置

plugins:[

new CleanWebpackPlugin(['dist']), //传入数组,指定要删除的目录

]

二、HotModuleReplacementPlugin

启用[热替换模块(Hot Module Replacement)],也被称为 HMR。

永远不要在生产环境(production)下启用 HMR

基本用法(Basic Usage)

启用 HMR 非常简单,在大多数情况下也不需要设置选项。

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

选项(Options)

包含如下选项:

  • multiStep (boolean):设置为true时,插件会分成两步构建文件。首先编译热加载 chunks,之后再编译剩余的通常的资源。
  • fullBuildTimeout (number):当 multiStep 启用时,表示两步构建之间的延时。
  • requestTimeout (number):下载 manifest 的延时(webpack 3.0.0 后的版本支持)。

这些选项属于实验性内容,因此以后可能会被弃用。就如同上文所说的那样,这些选项通常情况下都是没有必要设置的,仅仅是设置一下 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'\]  
})  
\]  
  
  

}