【问题标题】:How to use html-webpack-plugin variable inside <script>?如何在 <script> 中使用 html-webpack-plugin 变量?
【发布时间】:2018-11-09 10:33:26
【问题描述】:

我正在尝试通过变量所在的 html-webpack-plugin 在 &lt;script&gt; 标记内分配变量。 我可以很容易地在 html 标签中使用它,比如标题 &lt;%= htmlWebpackPlugin.options.applicationId %&gt;

我的 html-webpack-plugin 看起来像:

new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      applicationId : process.env.APPLICATION_ID ?process.env.APPLICATION_ID : 1,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: false
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),

我想在 index.html 页面上使用变量 applicationId 和以下脚本:

<script type="text/javascript">
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          document.write(xhr.responseText);
        }
      };
     var appId = <%= htmlWebpackPlugin.options.applicationId %>;
   xhr.open("GET","https://somesite.com/NavigationApi/api/content/get?applicationId=" + appId,false);
      xhr.send(null);
    </script>

【问题讨论】:

  • 当前将appId 设置为什么?

标签: javascript webpack html-webpack-plugin


【解决方案1】:

您可以设置隐藏输入并在那里设置appId,然后您可以使用javascript 检索该值(请确保在jquery 的onload 事件中执行此操作,或者如果您想使用vanilla JS,请使用DOMContentLoaded) ,希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 2018-03-19
    • 2016-11-16
    • 2016-01-16
    • 2016-11-26
    • 2021-05-25
    • 2020-01-16
    • 1970-01-01
    • 2023-02-11
    相关资源
    最近更新 更多