Webpack natively can only understand JS and JSON files. To support packaging of other types of files, you need to install the corresponding plug-in or loader.

If we need to package HTML files, we first need to install the HTML-webpack-plugin:

 npm install html-webpack-plugin -D
Copy the code

Webpack configuration

In Webpack introduction, we already know that we need to know the meaning of entry and output relative to Webpack configuration. Now we need to know about a new configuration item called plugins:

The Plugins option is used to define the WebPack build process in various ways. The various built-in plug-ins that come with WebPack can be used at compile time with this option.

After installing the HTmL-webpack-plugin, you need to configure it in the webpack.config.js file:

 // ...
 // 1. Import plug-ins
 const HtmlWebpackPlugin = require('html-webpack-plugin');
 ​
 module.exports = {
   // ...
   // 2. Configure plugins in plugins
   plugins: [
     new HtmlWebpackPlugin({
       template: 'index.html'.// Specify entry template file (relative to project root)
       filename: 'index.html'.// Specify the output file name and location (relative to the output directory)
       For additional configuration items of the plug-in, you can view the plug-in official documentation}})]Copy the code

Make sure the path and filename of the entry template file match the configuration, and then you can compile.

Configuration of multi-JS entry and multi-HTML case

If multiple HTML files need to be compiled and the files need to import different JS files, but by default, the packaged HTML file will import all the packaged JS files, we can specify chunk to allocate THE JS.

 const path = require('path');
 // 1. Import plug-ins
 const HtmlWebpackPlugin = require('html-webpack-plugin');
 module.exports = {
   // ...
   // 2. Configure JS entry (multiple entry)
   entry: {
     vendor: ['./src/jquery.min.js'.'./src/js/common.js'].index: './src/index.js'.cart: './src/js/cart.js'
   },
   // Configure the exit
   output: {
     filename: '[name].js'.path: path.resolve(__dirname, 'build/js')},// 3. Configure plug-ins
   plugins: [
     new HtmlWebpackPugin({
       template: 'index.html'.filename: 'index.html'.// Use chunk to specify which JS files to import
       chunk: ['index'.'vendor']}),// The plugin needs to be new as many times as it needs to compile HTML
     new HtmlWebpackPlugin({
       template: './src/cart.html'.filename: 'cart.html'.chunk: ['cart'.'vendor']]}})Copy the code

The HtmlWebpackPlugin needs to be new several times to compile as many HTML files as possible.

After the above configuration compiles successfully, the output looks like this:

Build | __ index. HTML # introduced index. Js and vendor. Js. | __ cart HTML # into cart. Js and vendor js | js | (vendor. Js # By jquery. Min. Js and common js generation | __ index. The js # by the index. The generated js | __ cart. Js # by cart. Js generationCopy the code