html-webpack-plugin

时间:2020-05-25
本文章向大家介绍html-webpack-plugin,主要包括html-webpack-plugin使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

插件的基本作用就是生成html文件,原理很简单:

将 webpack 中 entry 配置的相关入口 chunk 和 extract-text-webpack-plugin 抽取的 css 样式 插入到该组件提供的 template 或者 templateContent 配置项指定的内容基础上生成一个 html 文件,具体插入方式是将样式 link 插入到 head 元素中, script 插入到 head 或者 body 中。

实例化该插件可以不配置任何参数:

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

webpackConfg={

...

plugins:[

...

new htmlWebpackPlugin();

]

}

不配置任何选项的 html-webpack-plugin 插件,他会默认将webpack中的entry配置所有入口thunk和extract-text-webpack-plugin抽取的css样式都插入到指定的位置。

配置项:

title

生成的html文档的标题。配置该项,它并不会替换指定模板文件中的title元素的内容,除非html模板文件中使用了模板引擎语法来获取改配置项值,如下ejs模板语法形式:

<title>{%= o.htmlWebpacPlugin.options.title %}</title>

filename:输出文件的文件名称,默认为index.html,不配置就是该文件名;此外,还可以为输出文件指定目录位置,例如html/index.html

filename配置的html文件目录是相对于webpackConfig.output.path路径而言的,不是相对于当前项目目录结构的。

指定生成的html文件内容中的link 和 script 路径是相对于生成目录下的写路径的时候请写生成目录下的相对路径。

template:本地模板文件的位置,支持加载器(handlebars ejs undersore html等)

template配置项在html文件使用file-loader时,其所指定的位置找不到,导致生成的html文件内容不是期望的内容。

为template指定的模板文件没有指定任何loader的话,默认使用ejs-loader。

templateContent:可以指定模板的内容,不能与template共存。

inject:向template或者templateContent中注入所有静态资源,不同的配置值注入的位置不经相同。

1 true/body 所有js资源插入到body元素的底部

2 head: 所有的js资源插入到head元素中

3 false 所有的静态资源css和js都不会注入到模板文件中

favicon:添加特定favicon路径到输出的html文档中,这个同title配置项,需要在模板中动态获取其路径值

hash:true|false,是否为所有注入的静态资源添加webpack每次编译生成的唯一hash值,

chunks:允许插入到模板中的一些chunk,不配置此项默认会将entry中所有的thunk注入到模板中,在配置多个页面时,每个页面注入的thunk应该时不相同的,需要通过该配置为不同页面注入不同的thunk。

excludeChunks:这个与chunks配置项正好相反

chunksSortMode:none|auto|function,默认auto;允许指定的thunk在插入到html文档前进行排序

配置多个html页面

需要实例化该插件多次

...
    plugins: [
        new HtmlWebpackPlugin({
             template: 'src/html/index.html',
              excludeChunks: ['list', 'detail']
        }),
        new HtmlWebpackPlugin({
            filename: 'list.html',
            template: 'src/html/list.html',
            thunks: ['common', 'list']
        }), 
        new HtmlWebpackPlugin({
          filename: 'detail.html',
          template: 'src/html/detail.html',
           thunks: ['common', 'detail']
        })
    ]
    ...

如上例应用中配置了三个入口页面,index.html list.html detail.html,并且每个页面注入的thunk不尽相同;类似如果多页面应用,就需要为每个页面配置一个;

配置自定义模板

参考:https://www.cnblogs.com/wonyun/p/6030090.html

原文地址:https://www.cnblogs.com/xiaofenguo/p/12957845.html