How to bundle images using webpack?
Asked Answered
C

2

7

I am making an angular2 application with webpack module bundler. Now i have added file-loader for loading image files such as jpg, gif, png,etc. But when i run the build command the image files are not being bundled. Here is my configuration:

webpack.config.js (image loader config only)

{
    test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=.+)?$/,
    loader: 'file-loader?name=assets/[name].[hash].[ext]'
},

I have included images from a folder in my html template like this:

<img src="/asset/img/myImg.png"/>

in my css too:

#myBackground {
    background: background: #344556 url(/assets/img/background.jpg) center/cover;
}

But when i build the whole application, the images are not placed in the assets folder like i have specified in the webpack config.

Now the strangest thing is the same configuration is used for the fonts and they are being created inside the assets folder. This is my css for including the fonts in style.css:

@font-face {
    font-family: 'robotolight';
    src: url("../fonts/roboto-light-webfont.eot");
    src: url("../fonts/roboto-light-webfont.eot?#iefix") format("embedded-opentype"), url("../fonts/roboto-light-webfont.woff2") format("woff2"), url("../fonts/roboto-light-webfont.woff") format("woff"), url("../fonts/roboto-light-webfont.ttf") format("truetype"), url("../fonts/roboto-light-webfont.svg#robotolight") format("svg");
    font-weight: normal;
    font-style: normal;
 }

This font's all the files like svgs, ttf, woff, etc can be found in the assets folder after running the build.

Can anyone tell me why the images are not being created in the assets folder but the fonts file are, with the same config/loader.

Chromatin answered 9/1, 2017 at 9:30 Comment(0)
N
3

Might be a duplicate of this

Missing some loaders (extract-loader & html-loader)

Otherwise, if these static assets are included directly from the HTML, you could try to copy manually these assets via this handy webpack plugin

Neelyneeoma answered 9/1, 2017 at 16:15 Comment(1)
copying the files from src to dist did the trick for me (handlebars templates)Penny
G
0

As of Webpack 5 (released on October 10, 2020), this is now possible using Webpack's native asset modules.

Add a new rule set to the array module.rules inside your config.

{
  test: /\.(png|svg|jpg|jpeg|gif)$/i,
  type: 'asset/resource'
}

See the documentation on loading images for more information.

Gonad answered 29/5 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.