【问题标题】:`html-loader` overwrite `HtmlWebpackPlugin` `<%= %>` expression`html-loader` 覆盖 `HtmlWebpackPlugin` `<%= %>` 表达式
【发布时间】:2019-06-26 13:06:57
【问题描述】:

我在 webpack 中使用HtmlWebpackPlugin,下面是它的配置:

new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html',
        inject: 'body',
        sdk: '/mylib.js'
      })

在我的html 中,我将script 标记定义为:

<script src="<%= htmlWebpackPlugin.options.sdk %>"></script>

webpack 会将&lt;%= htmlWebpackPlugin.options.sdk %&gt; 替换为/mylib.js。但是,一旦我添加了html-loader 插件,它就不起作用了:

{
          test: /\.html$/,
          use: [
            {
              loader: 'html-loader',
              options: {
                attrs: 'img:src'
              }
            }
          ]
        }

我使用html-loader的原因是为了解析html文件上的img src标签。但它与HtmlWebpackPlugin&lt;%= ... %&gt; 表达式冲突。我怎样才能让它们都工作?

【问题讨论】:

    标签: webpack webpack-4 html-webpack-plugin webpack-html-loader


    【解决方案1】:

    您需要结合三个步骤。

    首先,你需要 HtmlWebpackPlugin。如https://stackoverflow.com/a/56264384/9363857所示

    第二,你激活html-loader。这导致了像

    这样的行的奇怪结果
    module.exports=.....
    

    在您的 html 中间(替换 require),这并不是您真正想要的。

    所以,第三,你需要把它翻译回html,你需要为它添加一个extract-loader。如:

    test: /\.(html)$/, use:  [ 'extract-loader',  { loader: 'html-loader' } ] 
    

    【讨论】:

      【解决方案2】:

      我为此找到的最简单的解决方案是使用 .ejs 扩展名重命名您的模板。 这将启动 html-webpack-plugin(因为它是一个后备的 ejs-loader),然后在处理完所有 之后,它将启动 html-loader。

      这样 html-webpack-plugin 会先运行,然后是 html loader。

      new HtmlWebpackPlugin({
          filename: 'index.html',
          template: 'index.html.ejs',  // don't forget to rename the actual file
          inject: 'body',
          sdk: '/mylib.js'
        })
      

      【讨论】:

      • 使用此方法,html-loader 将不再插入图片名称/链接。
      【解决方案3】:

      我会试试 html-loader 的 ignoreCustomFragments 属性。根据docs,您可以将其作为选项传递,加载程序会忽略某些部分,具体取决于正则表达式:ignoreCustomFragments: [/&lt;%=.*%&gt;/]

      【讨论】:

      • Webpack 5:ValidationError:无效的选项对象。 HTML Loader 已使用与 API 架构不匹配的选项对象进行初始化。 - 选项具有未知属性“ignoreCustomFragments”。这些属性是有效的:object { preprocessor?, sources?, minimize?, esModule? }
      猜你喜欢
      • 2023-01-01
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 2021-08-03
      • 2019-04-17
      相关资源
      最近更新 更多