webpack用index.htm中的bundle hash替换占位符

Whi*_*her 2 webpack html-webpack-plugin

我的目标是替换像这样的字符串

<!--configjs-->
Run Code Online (Sandbox Code Playgroud)

<script src="/api/config?bundle-hash"></script>
Run Code Online (Sandbox Code Playgroud)

在我的index.html文件中

我正在使用https://github.com/AngularClass/NG6-starter

plugins: [
    // Injects bundles in your index.html instead of wiring all manually.
    // It also adds hash to all injected assets so we don't have problems
    // with cache purging during deployment.
    new HtmlWebpackPlugin({
      template: 'client/index.html',
      inject: 'body',
      hash: true
    })
]
Run Code Online (Sandbox Code Playgroud)

cga*_*ian 6

你想使用html-webpack-plugin

配置插件,(我想你想把注入转为false来给你更好的控制).

// webpack.config.js
plugins: [new HtmlWebpackPlugin(
    {
       inject : false,
       template : 'index.html'
    }
)]
Run Code Online (Sandbox Code Playgroud)

在你的html模板中,按名称调出块.

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <script src="<%= htmlWebpackPlugin.files['bundle-hash'].entry %>"></script>
  </head>
  <body>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我不完全确定您的确切需求,但您可以只使用插件默认值并获得您想要的内容.该插件可以将现有的html文件作为模板,并在头部和脚本中注入CSS.如果你想要更多控制,你可以做我上面提出的建议.

  • 我不得不使用`htmlWebpackPlugin.files.chunks.main.entry`.只需将`<%= JSON.stringify(htmlWebpackPlugin.files)%>`放入html中,自己查看路径应该如何. (4认同)
  • 你知道有什么 webpack 插件可以像占位符一样用变量替换 `html-webpack-plugin` ,但是在任意文件上吗? (2认同)