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

前端 未结 3 1134
故里飘歌
故里飘歌 2021-01-01 00:09

I use Webpack along with the plugin html-webpack-plugin. Based on an environment variable, I want to inject a tag into th

3条回答
  •  离开以前
    2021-01-01 00:31

    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 tag with that information:

    
    
      
        
        <% if (htmlWebpackPlugin.options.author) { %>
        
        <% } %>
      
      
      
    
    

    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:

    
    

提交回复
热议问题