webpack常用的插件 htmlWebpackPlugin

webpack常用的插件 htmlWebpackPlugin

作用:该插件将为你生成一个 HTML5 文件,在执行webpack之后生成的build文件下只有一个js文件,它不会自动生成与之对应的html文件,所以我们需要让它在build文件夹之后再生成一个html,然后直接运行build文件夹里面的html就可以看到你想要的效果

1.1 安装 npm install --save-dev html-webpack-plugin

1.2 配置webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
  entry: 'index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'index_bundle.js',
  },
  plugins: [new HtmlWebpackPlugin()],
};

这将会生成一个包含以下内容的 build/index.html 文件:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>webpack App</title>
  </head>
  <body>
    <script src="index_bundle.js"></script>
  </body>
</html>

但是观察生成的html代码,会发现它只是生成了一个新的html,并没有将我们自己创建的html中的代码写入

1.3 配置 webpack.config.js 中的’HtmlWebpackPlugin’ plugins

文档:https://github.com/jantimon/html-webpack-plugin#options

plugins: [new HtmlWebpackPlugin({ template:'./index.html'} )],  // 选择一个你创建好的html作为插件的模板,将你写的代码复制到build文件夹下的index.html中

工作原理:其工作原理就相当于在build文件夹下新建了一个index.html,然后你在HtmlWebpackPlugin这个插件中给它指定了一个模板,然后他就会去你指定的模板中寻找你编写的代码,然后将它们全部复制下来,粘贴到build中的html中

测试:运行webpack看是否生成html文件,


版权声明:本文为Xtianbaizhou原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。