search
HomeWeb Front-endHTML TutorialDetailed code analysis of html-webpack-plugin

作用

直接为项目生成一个或多个HTML文件(HTML文件个数由插件实例的个数决定),并将webpack打包后输出的所有脚本文件自动添加到插件生成的HTML文件中。通过配置,可以将根目录下用户自定义的HTML文件作为插件生成HTML文件的模板。另外,还可以通过向插件传递参数,控制HTML文件的输出。

用法:

  1. 第一步:在项目根目录下安装插件:

    cnpm install html-webpack-plugin --save-dev
  2. 第二步:在webpack配置文件头部require html-webpack-plugin模块,并保存引用至htmlWebpackPlugin变量

    var htmlWebpackPlugin = require('html-webpack-plugin');
  3. 第三步:为webpack配置文件暴露的对象添加一个plugins属性,属性值为一个数组,将新建的html-webpack-plugin对象实例添加到数组中。若不传入任何参数,那么插件将生成默认的html文件。

    module.exports = {
     entry: {
         main:'./src/script/main.js'
     }, 
     output: {
         path: './dist',
         filename: 'js/[name].bundle.js'
     },
     plugins:[
         new htmlWebpackPlugin()
         ]
    }
  4. 第四步:配置参数。为新建的对象实例传入一个对象字面量参数,初始化对象实例的属性。

    module.exports = {
     ... ,
     plugins:[
         new htmlWebpackPlugin({
             filename:'index.html',
             template:'template.html', 
             inject:false,
             title:'webpack is good',
             chunks:['main']
         })
         ]
    }

htmlWebpackPlugin对象

htmlWebpackPlugin对象有两个属性,一个是files,一个是options。files和options的属性值都是对象。通过EJS语法,可以在HTML模板文件(template.html)中遍历这两个属性,查看其详情:

<% for(var key in htmlWebpackPlugin.files) { %>
    <%= key %> : <%= JSON.stringify(htmlWebpackPlugin.files[key]) %>    //将对象或数组转换为JSON字符串。
<% } %>

<% for(var key in htmlWebpackPlugin.options) { %>
    <%= key %> : <%= JSON.stringify(htmlWebpackPlugin.options[key]) %>    
<% } %>

遍历后的结果如下:

"htmlWebpackPlugin": {
  "files": {
    publicPath : "", 
    "css": [],
    "js": [ "js/main.ae8647e767cd76e54693.bundle.js"],
    "chunks": {
      "main": {
        "size":23,
        "entry": "js/main.ae8647e767cd76e54693.bundle.js", 
        "css": [],
        "hash":"ae8647e767cd76e54693",
      }
    },
    manifest : ""
  },
  "options":{
        template : "C:\\dev\\webpack-demo\\node_modules\\.2.28.0@html-webpack-plugin\\lib\\loader.js!c:\\dev\\webpack-demo\\index.html",    
    filename : "index.html",    
    hash : false,    
    inject : false,    
    compile : true,    
    favicon : false,    
    minify : false,        
    cache : true,    
    showErrors : true,    
    chunks : ["main"],    
    excludeChunks : [],    
    title : "webpack is good",    
    xhtml : false    
    }
}

参数说明:

  • title: title值用于生成的HTML文档。

  • filename: 将生成的HTML写入到该文件中。默认写入到index.html中。你也可以在这儿指定子目录 (eg: assets/admin.html)。

  • template: Webpack require path 到 template中。 详情查阅 docs

  • inject: true | 'head' | 'body' | false添加所有的静态资源(assets)到模板文件或templateContent 。当传入true'body'时,所有javascript资源将被放置到body 元素的底部。 当传入'head'时, 所有的脚本将被放置到head元素中。

  • favicon: 添加指定的favicon path到输出的html文件。

  • minify: {...} | false 传入一个html-minifier 对象选项来压缩输出的html文件。

  • hash: true | false 如果值为true,就添加一个唯一的webpack compilation hash给所有已included的 scripts 和 CSS 文件。这对缓存清除(cache busting)十分有用。

  • cache: true | false 如果为true (默认),只要文件被更改了就emit(发表)文件。

  • showErrors: true | false如果为true (默认),详细的错误信息将被写入到HTML页面。

  • chunks:允许你只添加某些chunks (e.g. only the unit-test chunk)

  • chunksSortMode: 在chunks被include到html文件中以前,允许你控制chunks 应当如何被排序。允许的值: 'none' | 'auto' | 'dependency' | {function} - 默认值: 'auto'

  • excludeChunks: 允许你跳过某些chunks (e.g. don't add the unit-test chunk)

  • xhtml: true | false 如果为true, 将 link 标签渲染为自闭合标签, XHTML compliant。 默认是 false。

template参数

由于html-webpack-plugin直接生成的HTML文件十分简单,不能满足项目需求,因此我们通常会配置template参数,将该参数值设置为我们已创建好的HMTL模板文件相对于根目录的相对路径。

    template:&#39;template.html&#39;

由于html-webpack-plugin支持EJS模板语法,因此在模板文件中,我们可以使用EJS模板语法来获取htmlWebpackPlugin对象中的数据,以此来控制html的输出。

chunks或excludeChunks参数

chunks或excludeChunks参数限定了HTML模板文件中能够包含的打包后的脚本文件。该参数对脚本的自动注入或手动注入都有限定作用。

inject参数

注意下面两种情况:

  1. 若inject值为false,那么所有打包后的脚本文件都不会被自动添加到HTML模板文件中。此时你需要在模板文件中通过EJS语法,在需要的位置处,手动添加相应的脚本文件,若不添加,打包后的脚本文件将不会出现在HTML模板文件相应的位置上。

    module.exports = {
    ...
     plugins:[
         new htmlWebpackPlugin({
             filename:&#39;c.html&#39;,
             template:&#39;index.html&#39;,
             title:&#39;this is c.html&#39;,
             inject:false,
             excludeChunks:[&#39;a&#39;,&#39;b&#39;]
         })
     ]
    }
  2. 若inject未设置,或设置了非false的值,那么所有打包后的脚本文件都会被自动添加到HTML模板文件中。在这种场景下,HTML模板文件中不能出现任何手动添加的打包后的脚本文件。因为后者会导致webpack报错或是出现脚本重复注入的情况。

    module.exports = {
    ...
     plugins:[
         new htmlWebpackPlugin({
             filename:&#39;admin.html&#39;,
             template:&#39;index.html&#39;,
             inject:&#39;head&#39;,
             chunks:[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]
         })
     ]
    }

当inject未设置,或设置了非false的值时:若此时HTML模板文件中已有被手动添加的打包后的脚本文件,那么:

  • 当该脚本文件所对应的chunk与chunks或excludeChunks参数所限定的chunk不一致时,webpack会报错;

  • 当手动添加的位置与inject参数值所指示的位置不一致时,webpack也会报错。

  • 若都一致,那么手动添加的脚本文件也会被注入到HTML模板中,从而出现脚本重复注入的情况。

结论:在同一HTML模板文件中,自动添加已打包的脚本文件与手动添加已打包的脚本文件不能并存,这两项操作只能选其一。

特殊情况:使用EJS语法向HTML模板文件手动添加打包后的脚本文件:

1.由于inject参数不能被同时设置为'head'和'body',因此,当有的打包后的脚本文件需要被添加到head标签,而另外的需要被添加到body标签中时,就需要手动向HTML模板注入脚本。

<head>
    ...
    <script src="<%= htmlWebpackPlugin.files.chunks.main.entry %>"></script>
</head>

<body>
<% for(var k in htmlWebpackPlugin.files.chunks){ %>
    <% if(k!==&#39;main&#39;){ %>
    <script src="<%= htmlWebpackPlugin.files.chunks[k].entry %>"></script>
    <% } %>
<% } %>
</body>

2.为了网页的加载性能,减少HTTP请求数,当有的打包后的脚本文件需要被内嵌到head标签中,而其余的需要以引用外部资源的方式添加到HTML模板中时,也需要手动向HTML模板注入脚本。

<head>
    ...
    <script type="text/javascript" src="<%= compilation.assets[htmlWebpackPlugin.files.chunks.main.entry.substr(htmlWebpackPlugin.files.publicPath.length)].source() %>"></script>
</head>

<body>
<% for(var k in htmlWebpackPlugin.files.chunks){ %>
    <% if(k!==&#39;main&#39;){ %>
    <script src="<%= htmlWebpackPlugin.files.chunks[k].entry %>"></script>
    <% } %>
<% } %>
</body>

生成多个HTML文件

如果我们开发的是一个多页面应用程序,那么我们就需要为不同的页面生成不同的HTML文件。通过向plugins数组添加多个插件实例就可以实现:

module.exports = {
  entry: &#39;index.js&#39;,
  output: {
    path: &#39;dist&#39;,
    filename: &#39;index_bundle.js&#39;
  },
  plugins: [
    new HtmlWebpackPlugin(), // Generates default index.html 
    new HtmlWebpackPlugin({  // Also generate a test.html 
      filename: &#39;test.html&#39;,
      template: &#39;src/assets/test.html&#39;
    })
  ]
}

       

The above is the detailed content of Detailed code analysis of html-webpack-plugin. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool