html-webpack-plugin的作用

html-webpack-plugin的主要作用就是在webpack构建后生成html文件,同时把构建好入口js文件引入到生成的html文件中。

安装html-webpack-plugin

Webpack 5

  npm i --save-dev html-webpack-plugin  

  yarn add --dev html-webpack-plugin

Webpack 4

  npm i --save-dev html-webpack-plugin@4
  yarn add --dev html-webpack-plugin@4

 webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    mode:"development",
    plugins: [
        new HtmlWebpackPlugin({
            filename:'index.html',
            template:'./public/index.html'
        })
    ]
}

项目文件目录结构:

执行webpack打包命令,在 ./dist 文件夹下会生成,main.js和index.html两个文件,index.html文件引入了main.js文件。

更多html-webpack-plugin设置:https://www.npmjs.com/package/html-webpack-plugin

建议打包输出请先使用clean-webpack-plugin插件清空目录。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐