James Monger
James Monger

Reputation: 10685

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?

Upvotes: 0

Views: 2259

Answers (2)

James Monger
James Monger

Reputation: 10685

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.

Upvotes: 1

Dan
Dan

Reputation: 794

You could set a variable with the path and reference that.

var imagePath = '../assets/images/';
require(imagePath + 'some-image.png');

or with ES6 template strings

const imagePath = '../assets/images/';
require(`#{imagePath}some-image.png`);

Upvotes: 0

Related Questions