Snowman
Snowman

Reputation: 32091

Webpack - importing from absolute path

I have a scss file located in src/app/views/style.scss.

I also have an image file in src/app/images/icon.png.

I want to do something like this: (notice the absolute path)

background-image: url("/images/icon.png");

However, this doesn't work obviously because I need to use a relative path to go up to the parent directory.

This works (a relative path), but is undesirable:

background-image: url("../images/ico-add.png");

How can I configure Webpack to respect absolute URLs in nested files?

Upvotes: 4

Views: 2558

Answers (2)

Young Zhao
Young Zhao

Reputation: 11

This can be configured in css loader:

https://github.com/webpack/css-loader#root-relative-urls

"For urls that start with a /, the default behavior is to not translate them:"

So I assume you want to translate urls start with a /. You can add a root parameter to the css loader.

Upvotes: 0

Snowman
Snowman

Reputation: 32091

The problem I was having was that when importing one scss file into another that wasn't necessarily in the same directory, I would get issues. So I thought using absolute URLs would solve this issue.

I was able to find a different solution to this problem. Using the resolve-url-loader, and setting webpack.config.js to use this:

{
        test: /\.scss$/,
        loaders: ["style", "css", 'resolve-url', "sass?sourceMap"]
}

Relative paths were now resolved properly depending on the original file the url(...) statement was in.

I would still be interested however in a solution to the question of using absolute paths.

Upvotes: 1

Related Questions