在webpack中使用html-webpack-plugin和string-replace-loader

10

我正在尝试替换index.html中的一个变量,它看起来像这样:

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

在配置文件中,我使用:

  {
    test: /index\.html$/,
    loader: 'string-replace',
    query: {
      search: '$variable',
      replace: 'stuff to inject',
    },
  }

loaders数组中,然后在plugins中:

new HtmlWebpackPlugin({
  template: conf.path.src('src/index.html'),
  inject: true,
})

但是这个设置导致了以下错误:

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.

你有什么想法是什么原因引起的或者如何进行调试吗?


为了调试,我正在使用 iron-node,它允许在 Node 模块中添加调试器语句。 - jantimon
3个回答

6
这是由于 string-replace-plugin 要求一个输出字符串的模块,所以出现了此问题。您需要将 HTML 文件转换为 CommonJS 模块。
例如,可以使用 raw-loader 来解决此问题:
首先,在 HTML 中添加引号到 content 属性中。
<meta name='author' content='$variable'>`

并且

{
    test: /index\.html$/,
    loader: 'string-replace?search=$variable&replace=stuff to inject!raw'
  }

不错 - 你认为我们能否改进html-webpack-plugin以改善错误信息? - jantimon

3

Konstantin的回答很好,并且适用于替换一个值。我想要替换多个值,所以将以下内容添加到我的loaders数组中:

  {
    test: /\.html$/,
    loader: 'raw'
  },
  {
    test: /\.html$/,
    loader: 'string-replace',
    query: {
      multiple: [
        {search: '$variable1', replace: 'replacement 1'},
        {search: '$variable2', replace: 'replacement 2'}
      ]
    }
  }

关键变化是首先通过 raw loader 运行您的 html 文件,然后您可以使用所有常规的 string-replace-loader 配置。

1
这个在 webpack 1.X 中可以工作,但我认为它不能与 webpack 2 和 3 兼容。 - SharpCoder

2

这是对@Jonathon Blok的答案进行更新,适用于Webpack 4,并进行了一些微小的修改:

  • 必须npm install --save-dev string-replace-loader@2
  • 由于webpack@4的要求,必须使用'raw-loader''string-replace-loader'标识符。
  • 根据string-replace-loader文档,使用options:代替query:

针对Webpack 4

{
  test: /.*\.html$/,
  loader: 'raw-loader',
},
{
  test: /.*\.html$/,
  loader: 'string-replace-loader',
  options: {
    multiple: [
      {search: '$variable1', replace: 'replacement 1'},
      {search: '$variable2', replace: 'replacement 2'}            ]
  }
}

与之前一样,关键变化在于首先将您的html文件通过原始加载器运行,然后您可以使用所有正常的配置来使用string-replace-loader。

对于Webpack 5

与上面相同的方法也适用于Webpack 5,尽管我没有测试过,可以通过省略@2并使用npm install --save-dev string-replace-loader安装string-loader。这是因为根据string-replace-loader文档,v3的string-replace-loader预计可以与Webpack 5+兼容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接