David.Woosley
David.Woosley

Reputation: 37

How to get webpack 4 to ignore image src

I'm using the CopyWebpackPlugin with Webpack 4 to copy an images folder to the dist folder in a production build, and I don't want Webpack to attempt to resolve or change <img src="./images/flower.png"> anywhere in the application. And I mean anywhere in any mode.

For example, if I use html-loader to load an HTML snippet into a parent HTML file, I don't want Webpack to touch the img src values in that snippet because the snippet and its associated images may have been created by a designer who knows nothing about Webpack. Moreover, the application may have a dozen or a hundred such snippets. I don't know yet.

The rule in the config file currently looks like this:

test: /\.(png|jpe?g|gif|svg)$/i,
use: [
  {
    loader: 'url-loader',
    options: {
      name: '[path][name].[ext]?hash=[hash:20]',
      esModule: false,
      limit: 8192
    }
  }
]

I presume I need to add, change or remove a simple option in the Webpack config file, but I don't know which one.

I'm a newbie to Webpack, and I welcome any advice on how to accomplish this.

Many thanks, David.

Upvotes: 1

Views: 2598

Answers (2)

Andrey
Andrey

Reputation: 11

Try to use this settings for webpack.config.js:

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: "html-loader",
        options: {
          // Disables attributes processing
          sources: false,
        },
      },
    ],
  },
};

Upvotes: 1

Ben Montgomery
Ben Montgomery

Reputation: 53

I had a similar issue and solved it by setting html-loader's attributes flag to false.

By default every loadable attribute (for example - < img src="image.png">) is imported (const img = require('./image.png') or import img from "./image.png""). You may need to specify loaders for images in your configuration (recommended file-loader or url-loader).

https://webpack.js.org/loaders/html-loader/#attributes

Upvotes: 3

Related Questions