【问题标题】:Use html-webpack-plugin with string-replace-loader in webpack在 webpack 中使用 html-webpack-plugin 和 string-replace-loader
【发布时间】:2016-11-16 12:33:22
【问题描述】:

我正在尝试替换 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,它允许将调试器语句添加到节点模块

标签: javascript html build webpack webpack-html-loader


【解决方案1】:

@Jonathon Blok 的答案的更新,但针对 Webpack 4,稍作修改:

  • 必须npm install --save-dev string-replace-loader@2
  • 不得不使用 'raw-loader''string-replace-loader' 标识符,因为 webpack@4 坚持。
  • 根据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文件,然后你可以使用所有正常的字符串替换加载器配置。

对于 Webpack 5

通过省略@2 并使用npm install --save-dev string-replace-loader 安装字符串加载器,Webpack 5 应该与上述相同,尽管我还没有对其进行测试。这是因为根据string-replace-loader docs,预计 v3 的 string-replace-loader 可以与 Webpack 5+ 一起使用。

【讨论】:

    【解决方案2】:

    康斯坦丁的回答很好,如果你想替换一个值,这很好。我想替换多个值,所以将以下内容添加到我的 loaders 数组中

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

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

    【讨论】:

    • 这在 webpack 1.X 中有效,但我认为它不适用于 webpack 2 和 3。
    【解决方案3】:

    这是因为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 以改善错误消息吗?
    猜你喜欢
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2018-03-03
    • 2018-03-19
    • 1970-01-01
    • 2015-10-10
    • 2018-06-27
    • 2018-04-17
    相关资源
    最近更新 更多