0
votes

I'm very new to Webpack and SCSS so I'm not even sure how to ask this question well. In essence, I have a bunch of SCSS files that configure image references. For example:

.someClass {
  background-image: url(img/some-image.png);
}

Which works fine as long as I'm referencing images served on the same server as the CSS. However, I'd like to serve the images from a separate CDN. One of the suggestions I've run across is to set a "cdnPath" variable using sass-loader and adjust the references like so:

/* webpack.config.js /*
{
  loader: "sass-loader",
  options: {
    data: "$cdnPath: https://cdn-path.com;"
  }
}

/* some.scss */
.someClass {
  background-image: url($cdnPath + "img/some-image.png");
}

However, to me this seems like an error-prone solution. I'm wondering if there's a way to automatically prepend the CDN path to these url references. Is there a better way that I'm unaware of?

1

1 Answers

0
votes

One way is with a SASS function:

$cdn-url: "https://cdn-path.com";

@function get-asset($local-path) {
  @return url($cdn-url + $local-path);
}

.some-class {
  background-image: get-asset("/static/images/image.png");
}

// Output:
//
// .some-class {
//   background-image: url(https://cdn-path.com/static/images/image.png);
// }