返回

Webpack 4 构建大型项目实践 / 巧妙处理 HTML

前端

引言

在上一节中,我们提到Webpack只能处理Javascript文件,这显然不能满足用户的日常使用需求。因此,Webpack提供了loader和plugins两个配置选项,用于扩展Webpack的处理类型。本节将介绍HtmlWebpackPlugin,它专门用于处理HTML文件。

HtmlWebpackPlugin 简介

HtmlWebpackPlugin是一个Webpack插件,它允许你在Webpack构建过程中自动生成HTML文件。这个插件可以帮助你简化项目构建流程,提高开发效率。

使用 HtmlWebpackPlugin

安装 HtmlWebpackPlugin

首先,你需要安装HtmlWebpackPlugin。你可以使用以下命令进行安装:

npm install html-webpack-plugin --save-dev

配置 HtmlWebpackPlugin

在你的Webpack配置文件中,你需要配置HtmlWebpackPlugin。你可以使用以下配置:

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

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: './dist/index.html',
    }),
  ],
};

在上面的配置中,我们指定了HTML模板文件(template)和生成的HTML文件名(filename)。

使用 HtmlWebpackPlugin 生成 HTML 文件

在Webpack构建过程中,HtmlWebpackPlugin会自动生成HTML文件。你可以通过以下命令构建项目:

webpack

构建完成后,你可以在dist文件夹中找到生成的HTML文件。

总结

HtmlWebpackPlugin是一个非常有用的Webpack插件,它可以帮助你简化项目构建流程,提高开发效率。如果你正在使用Webpack构建项目,强烈建议你使用HtmlWebpackPlugin。

实例

以下是一个使用HtmlWebpackPlugin构建项目的示例:

// 项目目录结构

├── package.json
├── src
│   ├── index.js
│   └── index.html
└── webpack.config.js

// package.json

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "My project",
  "author": "Me",
  "license": "MIT",
  "devDependencies": {
    "html-webpack-plugin": "^4.0.0",
    "webpack": "^4.0.0",
    "webpack-cli": "^3.0.0"
  }
}

// src/index.js

console.log('Hello, world!');

// src/index.html

<!DOCTYPE html>
<html>
  <head>
    
  </head>
  <body>
    <h1>Hello, world!</h1>
  </body>
</html>

// webpack.config.js

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

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: __dirname + '/dist'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: './index.html'
    })
  ]
};

// 运行构建命令

webpack

构建完成后,你可以在dist文件夹中找到生成的index.html文件。