How to inject data to SCSS file from webpack

Sky Bit
2 min readAug 28, 2019

Hi, Developers,

In a site, where you have to use assets, those are hosted somewhere else other than the application server, it might be a headache to link those from the CSS stylesheets. You might be thinking to link those from JS files dynamically, or use inline CSS in HTML files.

But what if the number of assets are quite large(may be some 100s) and the number of times those are used is more than enough. So you have to write them by thousands of times.

Now, if you use CDNs (i.e. AWS S3 etc) to link them, you have to prepend that base url to all asset urls in CSS file. But, what if at any point, your CDN url is changed. You must have to change the base URL at every single occurence in the code. That might be a severe headache.

There is a solution to it. You can use a variable in the Stylesheet file. Not in CSS, but you can use SCSS. You can check what an SCSS is. (It is a compilable CSS, where you can define variables, write logics, conditions etc.) In this file, if you can manage to add a variable with the CDN link, you can use that variable and prepend to all the assets to use the links.

But It may not be an ideal idea to define such values in SCSS files. Sometimes it may be changed. You may define it on .env file and want to use it everywhere on the code. Now, if you are using webpack to compile SCSS to CSS, you can use syntax like:

// The input data to be sent to sass file
const mydata = 'http://awscdn.com/storage/';
mix.sass('/assets/sass/app.scss', '/public/js/app.css', {
data: '$awsUrl = ' + mydata +';'
});

Here, mydata is the data taht we want to send to assets. In second line, we are compiling the asset from dynamic SCSS to static usable CSS. The 3rd parameter to mix.sass() will be an object, that contains one data property containing information. If you want to send data from .env, you may use like:

const mydata = process.env.AWS_CDN_BASE_PATH;

In this way, we can pass data to the SCSS file. In the SCSS file, you can use $variable, where you want to use it. In this way, the data will be dynamic and will be updated on compilation of assets, when there is a change in the data.

In the SASS file, you can use the parameter as:

.element {
background-image: url($awsUrl + 'images/menu-bg.jpg');
}

Here, the $awsUrl variable is defined in our compilation file.

The output CSS file content for this element will be:

.element {
background-image: url(http://awscdn.com/storage/images/menu-bg.jpg);
}

Hooray, you have now achieved your goal.

Good luck…

Thanks
Sky Bit
skybit.bbsr@gmail.com

--

--