在webpack中使用带有string-replace-loader的html-webpack-plugin

wap*_*300 6 html javascript build webpack webpack-html-loader

我正在尝试替换index.html中的变量,如下所示:

<meta name='author' content=$variable>

在配置文件中我使用:

  {
    test: /index\.html$/,
    loader: 'string-replace',
    query: {
      search: '$variable',
      replace: 'stuff to inject',
    },
  }
Run Code Online (Sandbox Code Playgroud)

loaders数组中,然后在plugins:

new HtmlWebpackPlugin({
  template: conf.path.src('src/index.html'),
  inject: true,
})
Run Code Online (Sandbox Code Playgroud)

但是这个设置导致:

ERROR in ./~/html-webpack-plugin/lib/loader.js!./src/index.html Module parse failed (...) Unexpected token (1:0) You may need an appropriate loader to handle this file type.

您是否有任何想法可能是由此引起的或如何调试?

Kon*_*tin 6

这是因为string-replace-plugin期望一个模块导出一个字符串.您应该将HTML文件转换为CommonJS模块.

例如,这是使用的方式raw-loader:

首先,在html中为content属性添加引号

<meta name='author' content='$variable'>`
Run Code Online (Sandbox Code Playgroud)

{
    test: /index\.html$/,
    loader: 'string-replace?search=$variable&replace=stuff to inject!raw'
  }
Run Code Online (Sandbox Code Playgroud)