Search code examples
javascriptwebpackbundlebundling-and-minification

Webpack resolve images in certain directory


I have my images in /assets/images, and my code in /src.

To reference the images from /src, I have to currently do this:

require("../assets/images/some-image.png");

Is there a way that I can simplify this so that I don't need to specify the image path? Potentially just requiring image!some-image.png?


Solution

  • I managed to achieve this by using resolve.alias:

    resolve: {
        alias:{
            "~images": path.resolve("./assets/images")
        },
        extensions: [ '', '.js', '.jpg' ]
    }
    

    I can then use require("~images/test.jpg"); to get me ./assets/images/test.jpg.