繁体   English   中英

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

[英]Use html-webpack-plugin with string-replace-loader in webpack

我正在尝试替换 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.

你有什么想法这可能是由什么引起的,或者我该如何调试?

这是因为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'
  }

Konstantin 的答案很好用,如果您想替换一个值,这很好。 我想替换多个值,因此将以下内容添加到我的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所有正常配置。

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

  • 必须npm install --save-dev string-replace-loader@2
  • 必须使用'raw-loader''string-replace-loader'标识符,因为 webpack@4 坚持。
  • 使用的options:而不是query:根据string-replace-loader文档。

对于 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-replace-loader 的 v3 预计可以与 Webpack 5+ 一起使用,根据string-replace-loader 文档

暂无
暂无

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

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