作用

  1. devServer时,根据模板在项目的根目录下生成html文件。(类似于webpack-dev-server在内存中生成bundle.js)。
  2. devServer时,对html文件自动引入bundle.js文件。
  3. 打包时,自动生成index.html文件。 :::warning 使用这个插件时,就不用在index.html文件中引入 bundle.js 的标签。 :::

安装

  1. npm i html-webpack-plugin -D

配置

webpack.config.js 中的 plugins 节点下配置:

  1. const path = require('path')
  2. const HtmlWebpackPlugin = require('html-webpack-plugin')
  3. module.exports = {
  4. entry: './src/index.js',
  5. output: {
  6. path: path.join(__dirname, '/dist/'),
  7. filename: "bundle.js"
  8. },
  9. mode: 'development',
  10. plugins: [
  11. // 配置 html-webpack-plugin
  12. new HtmlWeabpackPlugin({
  13. filename: 'index.html', // 在内存中生成的文件名
  14. template: './src/index.html' // 模板,以磁盘上的这个文件为模板,不用引入 bundle.js
  15. })
  16. ],
  17. // 配置 webpack-dev-server
  18. devServer: {
  19. open: true,
  20. compress: true,
  21. hot: true,
  22. port: 3000,
  23. contentBase: './src'
  24. }
  25. }