How to add custom meta tags to html-webpack-plugin?

I am using Webpack along with a plugin html-webpack-plugin

. Based on the environment variable, I want to insert a tag <meta></meta>

into the final file index.html

.

How to do it?

+3


source to share


1 answer


You can define your own template. It is briefly mentioned in Writing Your Own Templates , in which you can pass any parameters you would like to use and use them in the template with htmlWebpackPlugin.options

:

htmlWebpackPlugin.options

: hash of parameters 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 to your template.

For example, you can define the author with an environment variable AUTHOR

and add the parameter AUTHOR

to the plugin:

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

      

In template.ejs

you can create a tag <meta>

with this 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 can use a file instead .html

and the plugin will fall back to ejs-loader

, but if you have one html-loader

configured for files .html

, it will use that instead of a backup, that won't work.

When AUTHOR

set, it will include a meta tag with author, otherwise it will not be included. Duration:

AUTHOR='Foo Bar' webpack

      

will include the following meta tag:

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

      

+13


source







All Articles