简体   繁体   English

HtmlWebpackPlugin无法解析模板中的自定义变量

[英]Custom variables in template are not resolved by HtmlWebpackPlugin

I need to add random variables to my template. 我需要在模板中添加随机变量。 It's an ejected Angular project that uses HtmlWebpackPlugin . 这是使用HtmlWebpackPlugin弹出的Angular项目。 My HtmlWebpackPlugin configuration looks like this: 我的HtmlWebpackPlugin配置如下所示:

new HtmlWebpackPlugin({
  "filename": "./index.html",
  "hash": false,
  "inject": false,
  "compile": true,
  "favicon": false,
  "minify": false,
  "template": "./src/index.html",
  "cache": true,
  "showErrors": true,
  "chunks": "all",
  "excludeChunks": [],
  "myHash": Math.random().toString(36).slice(2),
  "xhtml": true,
  "chunksSortMode": function sort(left, right) {
    let leftIndex = entryPoints.indexOf(left.names[0]);
    let rightindex = entryPoints.indexOf(right.names[0]);
    if (leftIndex > rightindex) {
      return 1;
    }
    else if (leftIndex < rightindex) {
      return -1;
    }
    else {
      return 0;
    }
  }
})

myHash is the variable I need to add to template. myHash是我需要添加到模板的变量。

For some reason, this doesn't work: 由于某些原因,这不起作用:

<p><%= htmlWebpackPlugin.options.myHash %></p>

The generated Html looks like same: <p><%= htmlWebpackPlugin.options.myHash %></p> 生成的HTML看起来像一样: <p><%= htmlWebpackPlugin.options.myHash %></p>

When I had very similar (extrapolating <%=htmlWebpackPlugin.files.webpackManifest%> ) problem in webpack 1, I solved it by excluding html-file from html-loader: 当我在webpack 1中遇到非常相似的问题(推断<%=htmlWebpackPlugin.files.webpackManifest%> )时,我通过从html-loader中排除html-file来解决了这个问题:

{
                test: /\.html$/,
                use: [{
                    loader: 'html-loader',
                    options: minifyHtmlOpts
                }],
                // excluding, so ejs loader will be used for these pages
                exclude: /index.html/
            }

And it still works with webpack 3. 它仍然适用于webpack 3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM