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/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值