plugins会自动帮忙干一些事情,使打包更加便捷
1.html-webpack-plugin
自动创建index.html并将打包后的bundle.js引入进来,另外它还可以配置模板文件。html-webpack-plugin是在打包之后运行的。
plugins: [new HtmlWebpackPlugin({template: 'src/index.html'})]
2.clean-webpack-plugin
在打包之前,自动清空dist目录下所有文件。配置如下
const { CleanWebpackPlugin } = require('clean-webpack-plugin');const webpackConfig = {plugins: [new CleanWebpackPlugin(),],};module.exports = webpackConfig;
注意:这是最新版的clean-webpack-plugin的配置,不要在括号里加[‘dist’]!
3.webpack-dev-server
监听代码变化,开启一个web服务器。改变src下的代码时,会自动打包并刷新浏览器! 注意这里:打包的代码并不会在dist目录下,而是会在电脑的内存中保存
devServer: {contentBase: './dist',open: true,port: 8080},
用express模拟webpack-dev-server功能
const express = require('express')const webpack = require('webpack')const webpackDevMiddleware = require('webpack-dev-middleware')const config = require('./webpack.config')const complier = webpack(config)const app = express()app.use(webpackDevMiddleware(complier, {publicPath: config.output.publicPath}))app.listen(8080,()=>{console.log('sever is running');})
4.HotModuleReplacementPlugin
这个插件是webpack内置插件,无需下载,直接配置。
作用是做热更新,局部刷新代码改变的部分,不会全局刷新页面
具体配置如下:
const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin')const {CleanWebpackPlugin} = require('clean-webpack-plugin')+ const webpack = require('webpack')module.exports = {entry: './src/index.js',devServer: {contentBase: './dist',open: true,+ hot: true,+ hotOnly: true},module: {rules: [...]},plugins: [new HtmlWebpackPlugin({template: 'src/index.html'}),new CleanWebpackPlugin(),+ new webpack.HotModuleReplacementPlugin()],output: {publicPath: '/',filename: 'build.js',path: path.resolve(__dirname, 'dist')},}
