如何在html-webpack-plugin中注入自定义元标记? [英] How to inject custom meta tags in html-webpack-plugin?

查看:580
本文介绍了如何在html-webpack-plugin中注入自定义元标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Webpack和插件 html-webpack-plugin 。基于环境变量,我想将< meta>< / meta> 标记注入最终的 index.html file。

I use Webpack along with the plugin html-webpack-plugin. Based on an environment variable, I want to inject a <meta></meta> tag into the final index.html file.

我该怎么做?

推荐答案

您可以定义自己的模板。您可以在编写自己的模板中简要提及传递你想要的任何选项并在模板中使用它们 htmlWebpackPlugin.options

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 :传递给插件的选项哈希。除了此插件实际使用的选项之外,您还可以使用此哈希将任意数据传递到您的模板。

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.

例如您可以使用环境变量 AUTHOR 定义作者,并为插件添加 author 选项:

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
})

template.ejs 中你可以使用以下信息创建< meta> 标记:

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>

您可以使用 .html 文件代替并且插件将回退到 ejs-loader ,但如果您为 html-loader > .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.

AUTHOR 设置它将包含作者的元标记,否则它不包括在内。正在运行:

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

AUTHOR='Foo Bar' webpack

将包含以下元标记:

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

这篇关于如何在html-webpack-plugin中注入自定义元标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆