webpack的html模板中插入变量写法

发布时间 2023-11-22 09:13:00作者: 看风景就

vue-cli文档中的描述如下

Index 文件#

public/index.html 文件是一个会被 html-webpack-plugin 处理的模板。在构建过程中,资源链接会被自动注入。另外,Vue CLI 也会自动注入 resource hint (preload/prefetch、manifest 和图标链接 (当用到 PWA 插件时) 以及构建过程中处理的 JavaScript 和 CSS 文件的资源链接。

插值#

因为 index 文件被用作模板,所以你可以使用 lodash template 语法插入内容:

  • <%= VALUE %> 用来做不转义插值;
  • <%- VALUE %> 用来做 HTML 转义插值;
  • <% expression %> 用来描述 JavaScript 流程控制。

除了被 html-webpack-plugin 暴露的默认值之外,所有客户端环境变量也可以直接使用。例如,BASE_URL 的用法:

<link rel="icon" href="<%= BASE_URL %>favicon.ico">

更多内容可以查阅:

1. html可以插入那些变量

1.1 htmlWebpackPlugin本身的变量

htmlWebpackPlugin.options

htmlWebpackPlugin.tags

htmlWebpackPlugin.files

1.2 webpack的对象

webpackConfig对象

compilation对象

The following variables are available in the template by default (you can extend them using the templateParameters option):

  • htmlWebpackPlugin: data specific to this plugin

    • 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.

    • htmlWebpackPlugin.tags: the prepared headTags and bodyTags Array to render the <base><meta><script> and <link> tags. Can be used directly in templates and literals. For example:

      <html>
        <head>
          <%= htmlWebpackPlugin.tags.headTags %>
        </head>
        <body>
          <%= htmlWebpackPlugin.tags.bodyTags %>
        </body>
      </html>
    • htmlWebpackPlugin.files: direct access to the files used during the compilation.

      publicPath: string;
      js: string[];
      css: string[];
      manifest?: string;
      favicon?: string;
  • webpackConfig: the webpack configuration that was used for this compilation. This can be used, for example, to get the publicPath (webpackConfig.output.publicPath).

  • compilation: the webpack compilation object. This can be used, for example, to get the contents of processed assets and inline them directly in the page, through compilation.assets[...].source() (see the inline template example).

详细可参考 html-webpack-plugin模板文档 和 模板变量examples 

2. 区分开发环境和生产环境的变量写法

在 html 标签里面这样使用

<% if (process.env.NODE_ENV === 'development') { %>
  <script src="<%= BASE_URL %>libs/vue/vue.js"></script>
  <% } else { %>
  <script src="<%= BASE_URL %>libs/vue/vue.min.js"></script>
  <% }
%>

在 script 脚本里面这样使用

<script>
    if ('<%= process.env.NODE_ENV %>' === 'development') {
      window.SITE_CONFIG['apiURL'] = '/api';  
    }
    else {
      window.SITE_CONFIG['apiURL'] = '/prod_api';         
    }
</script>

 

参考:webpack 如何在 html 页面里区分环境变量