M
M
mgfck2018-03-21 17:37:03
Sass
mgfck, 2018-03-21 17:37:03

How to attach SASS variable to background SVG (using Webpack)?

Hey!
Friends, I ask for help.
I have file.svg. There is CSS (SASS):
<svg fill="$main-color" ... </svg>

$main-color: red;
.item {
background: url('file.svg');
}

How to make the color in the file.svg file substituted from SASS, and then the svg file is included in the css as base64 or utf-8?
I use webpack to build.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mgfck, 2018-03-22
@mgfck

In general, he asked - he answered.
This is done like this:
install npm install svg-fill-loader --save
1. in the webpack config, write the rule for svg:

{
        test: /\.svg((\?.*)?|$)/,
        loaders: [
          'url-loader',
          'svg-fill-loader?selector=.svg-fill' // `selector` option will be used for all images processed by loader
        ]
      },

2. make a mixin in a file with scss variables:
$main-color: red;
@mixin apply-background-image($url, $color) {
   $base-color: str-slice(inspect($color), 2);
   background-image: unquote('url("' + $url + "?fill=%23" + $base-color +'")');
}

3. in the svg file, write the .svg-fill class for the entire svg or path (path class="svg-fill")
4. and do the color substitution in style.scss:
item {
  @include apply-background-image("./../assets/svg/item.svg", $main-color);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question