For local HTML/Sass/Css developement we use libsass (via Grunt) to compile our Sass files to Css. The Css background-image URL's are root relative.
Sass
$dir-img: /img;
.header {
background-image: url(#{$dir-img}/header.jpg);
}
We'd like to change the URL to use a CDN when compiling for production server:
background-image: url(http://media.website.com/img/header.jpg);
Is there some solution to pass-in a command-line argument TO Sass so Sass can use a Sass @IF
to switch the root-relative URL's to hard-coded CDN like URL's. Something like:
Command-line:
grunt sass:dist --cdnurl="http://media.website.com/img/"
Sass
Then Sass checks if the command-line argument was given:
@if using CDN {
$dir-img: cdnurl;
@else {
$dir-img: /img;
}
And then all IMG url's would use the CDN URL.
I couldn't find anything on libass command-line options to pass said vars. to Sass.
But eventually came up with a working version of my own! Have Grunt write a Sass config partial.
Pretty simple actually if your already using Grunt and Sass. We'd already had NodeJS and Grunt-cli installed on our staging (test) -server.
Sass setup
In Sass we already used a (larger) Sass config file which holds a few vars like:
_config.scss
This config file holds much more config settings but I've updated these vars. in this config file to:
Note the
@import
partial of_sourcepaths.scss
. This smaller partial file is generated by Grunt. The Sass!default;
is used as fallback vars. or you might not even need these anymore (are overwritten by Grunt).Grunt setup
On the Grunt side I added a custom task that is only executed on our staging (or test) -server (for example during a build process). On our local machine we keep using root-relative paths for local development.
Grunt custom target configuration
Example cdn Grunt target with hardcoded (http://cdn.website.com) or dynamic (via grunt.option command-line argument)
pathprefix
. See below at 'Running the Grunt task' how to run this. It also has a fallback|| ''
to empty, which actually resets the paths in the Sass config file to root-relative URL's.Grunt custom task
Then the required Grunt task (for configuration above). This Grunt task writes the Sass partial to disk.
Grunt aliased task
This creates a custom chained workflow of two tasks running after each other. The
sass:dist
is a regular Grunt task and target viagrunt-sass
(libsass) plugin. You are probably already using this.Running the custom Grunt task
The
pathprefix
var., viagrunt.option('pathprefix')
, in above Grunt custom target is provided viagrunt
command-line argument:This domainname can be changed by the staging (test) -server server-side-scripting language (like .NET/PHP/Ruby). The Sass config file
_sourcepaths.scss
is now changed by Grunt to:_sourcepaths.scss
Remember that
_sourcepaths.scss
is imported by Sass. The Grunt alias task then runs the usualsass:dist
target, which just re-compiles the Sass (on the staging / test server) WITH updated hard-coded CDN domain name paths in the Css.