plugins会自动帮忙干一些事情,使打包更加便捷

1.html-webpack-plugin

自动创建index.html并将打包后的bundle.js引入进来,另外它还可以配置模板文件。html-webpack-plugin是在打包之后运行的。

  1. plugins: [new HtmlWebpackPlugin({
  2. template: 'src/index.html'
  3. })]

配置好后打包文件自动生成的index.html如下图
image.png

2.clean-webpack-plugin

在打包之前,自动清空dist目录下所有文件。配置如下

  1. const { CleanWebpackPlugin } = require('clean-webpack-plugin');
  2. const webpackConfig = {
  3. plugins: [
  4. new CleanWebpackPlugin(),
  5. ],
  6. };
  7. module.exports = webpackConfig;

注意:这是最新版的clean-webpack-plugin的配置,不要在括号里加[‘dist’]!

3.webpack-dev-server

监听代码变化,开启一个web服务器。改变src下的代码时,会自动打包并刷新浏览器! 注意这里:打包的代码并不会在dist目录下,而是会在电脑的内存中保存

  1. devServer: {
  2. contentBase: './dist',
  3. open: true,
  4. port: 8080
  5. },

用express模拟webpack-dev-server功能

  1. const express = require('express')
  2. const webpack = require('webpack')
  3. const webpackDevMiddleware = require('webpack-dev-middleware')
  4. const config = require('./webpack.config')
  5. const complier = webpack(config)
  6. const app = express()
  7. app.use(webpackDevMiddleware(complier, {
  8. publicPath: config.output.publicPath
  9. }))
  10. app.listen(8080,()=>{
  11. console.log('sever is running');
  12. })

4.HotModuleReplacementPlugin

这个插件是webpack内置插件,无需下载,直接配置。

作用是做热更新,局部刷新代码改变的部分,不会全局刷新页面

具体配置如下:

  1. const path = require('path');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin')
  3. const {CleanWebpackPlugin} = require('clean-webpack-plugin')
  4. + const webpack = require('webpack')
  5. module.exports = {
  6. entry: './src/index.js',
  7. devServer: {
  8. contentBase: './dist',
  9. open: true,
  10. + hot: true,
  11. + hotOnly: true
  12. },
  13. module: {
  14. rules: [...]
  15. },
  16. plugins: [
  17. new HtmlWebpackPlugin({
  18. template: 'src/index.html'
  19. }),
  20. new CleanWebpackPlugin(),
  21. + new webpack.HotModuleReplacementPlugin()
  22. ],
  23. output: {
  24. publicPath: '/',
  25. filename: 'build.js',
  26. path: path.resolve(__dirname, 'dist')
  27. },
  28. }