search
HomeWeb Front-endJS TutorialLet's talk about how to compress and package html resources in webpack

How to compress and package html resources in webpack? The following article will give you a brief introduction to the method of compressing and packaging HTML resources with webpack. I hope it will be helpful to you!

Let's talk about how to compress and package html resources in webpack

Why do you need to package html resources?

When writing code, the js file under src is introduced. After being packaged by webpack, it is formed An entry file is created. At this time, the name and path of the js file in the html are incorrect, so webpack packaging is needed to replace the path of the js file introduced in the html.

The benefits of using webpack to package html are:

(1) The packaged js file can be automatically introduced into html

(2) HTML packaging It will still be generated in the build folder and put together with the packaged js files. In this way, when going online, we only need to copy the packaged and generated folders to the online environment.

(3) Will Help us compress html files

How to compress and package html resources in webpack

1. Install the plug-in

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

If we need to package HTML files, we first need to install html-webpack-pluginPlug-in:

npm install html-webpack-plugin -D

The role of this plug-in:

  • By default, an html file is created under the export, and then all JS/CSS resources are imported.

  • We can also specify an html file ourselves and add resources to this html file

2. Webpack.config.js configuration

Install the html-webpack-plugin plug-in Finally, you need to configure it in the webpack.config.js file:

 // ...
 // 1. 引入插件
 const HtmlWebpackPlugin = require('html-webpack-plugin');
 
 module.exports = {
   // ...
   // 2. 在plugins中配置插件
   plugins: [
     new HtmlWebpackPlugin({
       template: 'index.html', // 指定入口模板文件(相对于项目根目录)
       filename: 'index.html', // 指定输出文件名和位置(相对于输出目录)
       // 关于插件的其他项配置,可以查看插件官方文档
     })
   ]
 }

Detailed configuration link: https://www.npmjs.com/package/html-webpack- plugin

Make sure the path and file name of the entry template file are consistent with the configuration, and then you can compile.

3. Configuration of multiple JS entries and multiple HTML situations

When faced with the need to compile multiple HTML files, and the files need to introduce different JS files, but by default, the packaged HTML file will import all packaged JS files, we can specify chunk to allocate JS.

 const path = require('path');
 // 1. 引入插件
 const HtmlWebpackPlugin = require('html-webpack-plugin');
 module.exports = {
   // ...
   // 2. 配置JS入口(多入口)
   entry: {
     vendor: ['./src/jquery.min.js', './src/js/common.js'],
     index: './src/index.js',
     cart: './src/js/cart.js'
   },
   // 配置出口
   output: {
     filename: '[name].js',
     path: path.resolve(__dirname, 'build/js')
   },
   // 3. 配置插件
   plugins: [
     new HtmlWebpackPugin({
       template: 'index.html',
       filename: 'index.html',
       // 通过chunk来指定引入哪些JS文件
       chunk: ['index', 'vendor']
     }),
     // 需要编译多少个HTML,就需要new几次插件
     new HtmlWebpackPlugin({
       template: './src/cart.html',
       filename: 'cart.html',
       chunk: ['cart', 'vendor']
     })
   ]
 }

Tip: What you need to pay attention to here is how many HTML files you need to compile, how many times you need to new HtmlWebpackPlugin.

After the above configuration is compiled successfully, the output is as follows:

 build
 |__ index.html # 引入index.js和vendor.js
 |__ cart.html    # 引入cart.js和vendor.js
 |__ js
      |__ vendor.js # 由jquery.min.js和common.js生成
      |__ index.js    # 由index.js生成
      |__ cart.js       # 由cart.js生成

Compressed and packaged html resource example

1. webpack. config.js configuration

const HTMLWebpackPlugin = require('html-webpack-plugin')
...
 plugins: [
    // html-webpack-plugin  html 打包配置 该插件将为你生成一个 HTML5 文件
    new HTMLWebpackPlugin({
      template: "./index.html", // 打包到模板的相对或绝对路径 (打包目标)
      title: '首页', // 用于生成的HTML文档的标题
      hash: true,//true则将唯一的webpack编译哈希值附加到所有包含的脚本和CSS文件中。主要用于清除缓存,
      minify: {  // 压缩html
        collapseWhitespace: true, // 折叠空白区域
        keepClosingSlash: true,  // 保持闭合间隙
        removeComments: true,   // 移除注释
        removeRedundantAttributes: true, // 删除冗余属性
        removeScriptTypeAttributes: true,  // 删除Script脚本类型属性
        removeStyleLinkTypeAttributes: true, // 删除样式链接类型属性
        useShortDoctype: true, // 使用短文档类型
        preserveLineBreaks: true, // 保留换行符
        minifyCSS: true, // 压缩文内css
        minifyJS: true, // 压缩文内js
      }
    }),
  ],
...

2. At this time our index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>webpackDemo</title>
  </head>
  <body>
    <div id="app">
      html 打包配置
    </div>
  </body>
</html>

3. At this time our index.js

import &#39;./../css/index.less&#39;

function add(x,y) {
 return x+y
}
console.log(add(2,3));

3. Console webpack input package , found that there is an extra index.html in the packaged output file, the content is as follows

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>webpackDemo</title>
  <script defer src="index.js"></script></head>
  <body>
    <div id="app">
      html 打包配置
    </div>
  </body>
</html>

<script defer src="index.js"></script> is automatic The introduced

browser opened the packaged output index.html and found that the style had an effect, and the control unit also output normally:

Lets talk about how to compress and package html resources in webpack

Lets talk about how to compress and package html resources in webpack

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of Let's talk about how to compress and package html resources in webpack. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)