【问题标题】:How do I get webpack to rewrite image sources from pug?如何让 webpack 从 pug 重写图像源?
【发布时间】:2023-03-16 11:33:01
【问题描述】:

我正在编写一个 Angular 2 应用程序并希望将 pug 用于我的模板。我正在使用 webpack 构建解决方案。

如果我只是使用

{
    test: /\.pug$/,
    loader: 'pug-html-loader' 
},

在 webpack 配置文件中,图像文件的 URL 不会被重写。所以我试着把哈巴狗改成

img(src=require('../../public/images/logo.png'))

但这给出了这个错误:

Module build failed: TypeError: require is not a function

所以,我正在尝试以下 webpack 配置:

{
    test: /\.pug$/,
    loader: 'html?attrs=img:src!pug-html-loader' 
},

但这给出了这个错误:

ERROR in ./src/app/app.component.pug
Module not found: Error: Cannot resolve 'file' or 'directory' ./\"../../public/images/logo.png\" in /<app-path>/src/app
 @ ./src/app/app.component.pug 1:213-263

解决此问题的正确/最佳方法是什么?

【问题讨论】:

  • 使用html-loader 对我来说是正确的。但目前尚不清楚您尝试应用它的来源:它不再需要包含src=require(...),只需包含src=../../public/images/logo.png

标签: webpack pug-loader


【解决方案1】:

原来我打的是this bug in the pug-html-loader 包。通过使用这个包的不同版本,我让它工作了。

【讨论】:

    【解决方案2】:

    正如@andreypopp 所说,您不需要在哈巴狗中使用require()。而且,您确实需要将 pug-loader exports 选项设置为 false 以便它导出原始生成的 html 而不是 js 模块。这是我的配置:

      {
        test: /\.pug$/,
        loaders: [
          // html loader gets webpack to process <img> src
          'html-loader',
          // requires pretty option otherwise some spacing between elements is lost
          'pug-html-loader?{"pretty":true,"exports":false}'
        ],
        include: [sourcePath]
      },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      相关资源
      最近更新 更多