How to inject custom meta tags in html-webpack-plugin?

雨燕双飞 提交于 2019-12-03 15:52:13

You can define your own template. It's briefly mentioned in Writing Your Own Templates that you can pass any options you'd like to it and use them in the template with htmlWebpackPlugin.options:

htmlWebpackPlugin.options: the options hash that was passed to the plugin. In addition to the options actually used by this plugin, you can use this hash to pass arbitrary data through to your template.

For example you could define the author with the environment variable AUTHOR and add an author option to the plugin:

new HtmlWebpackPlugin({
  template: 'template.ejs',
  author: process.env.AUTHOR
})

In your template.ejs you can create a <meta> tag with that information:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <% if (htmlWebpackPlugin.options.author) { %>
    <meta name="author" content="<%= htmlWebpackPlugin.options.author %>">
    <% } %>
  </head>
  <body>
  </body>
</html>

You could use a .html file instead and the plugin will fallback to ejs-loader, but if you have html-loader configured for .html files, it will use that instead of the fallback, so the embedding won't work.

When AUTHOR is set it will include the meta tag with the author, otherwise it's not included. Running:

AUTHOR='Foo Bar' webpack

will include the following meta tag:

<meta name="author" content="Foo Bar">
   new HtmlWebpackPlugin({
     template: 'index.html',
     meta: {
       author: process.env.AUTHOR
     }
   });

resulting in the inclusion of the following within your head tag.

<meta name="author" content="Foo Bar">

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!