Search code examples
angularjswebpackhtml-webpack-pluginwebpack-plugin

Automatically require (or copy) all images that are referenced in HTML using Webpack


I just started to use Webpack with an Angular 1.x application, I have a working solution but rather than require my images (which would force them to be copied to the build directory) I was hoping to automatically parse the html and require all IMG tags.

I seemed to have found a module, although it doesn't seem to be maintained any more: https://github.com/webpack/html-loader

I was wondering what my options are here?

The option is to use the Webpack copy plugin to copy items into the build directory but this means I may copy things not in use.

I am just starting out with Webpack but what I see so far is great although it does require a different type of thinking to gulp.


Solution

  • I'm using html-loader in my dev config and it works fine for what i need. I'm not really sure why you want the images to be copied but if what you want is the imgs to be required, html-loader will achieve this for you. After that i use the url-loader like this:

       {
          test: /\.(png|gif|jpe?g)$/i,
          // if the file have ~50kb or less it's added to DOM as a data atributte, if not it's compressed as an image
          loader: 'url?limit=50000'  
       },
    

    If the image is bigger than 50kb it's copied to my build folder, if i'ts small i just let it be on the DOM as a data atributte reducing the number of http requests.

    I hope this help you somehow. Webpack is really hard at first but once you understand how it works you'll never go back.