Grunt task to make css urls relative to a main css file with @import rules
Grunt task to make css urls relative to a main css file with @import rules.
Install this grunt plugin next to your project's grunt.js gruntfile with:
npm install grunt-css-urls
Then add this line to your project's
finally define the task indicating where the css with the @import rules is located:
gruntinitConfigcssUrls:/* src *(required)*: The file location of the css with the @import rules. */src: "public/site.css";
Read the scenario described below to better understand how this task works combined together with the grunt-css task.
Lets imagine the following folder structure and css contents:
public├── css│ └─── common.css│ └─── views│ | └── products│ | └── show.css│ | └── img│ | └── product-icon.png├── img| └── logo.png| └── arrow.png├── vendor│ └─── jquery-plugin│ └── css│ └── jquery-plugin.css│ └── images│ └── plugin.png
and the html file including the css inclussions:
If we want to bundle all the thing into a sinle file e.g.: /public/site.css including the three css files described above, the images' references will not work as they will be now relative the new /public folder.
To solve the bundling issue we'll create a site.css file inside the public folder at the same level of css, img and vendor folders taking advantage of the @import css rules:
and reference it in the html:
By doing this we'll have a reference starting point to calcule the relative urls for the url references inside the css files and replace those with the corresponding location.
And here is where the grunt-css-url task will do the magic. The folowing sample uses also the grunt-css task to minify the css with the precedence defined in the site.css file:
var path = require'path';gruntinitConfigcssUrls:src: "public/site.css"cssmin:all:dest: 'public/site.min.css'var content = gruntfileread'public/site.css'toString;var files = ;contentreplace/@import\s+'/gimfilespushpathresolve'public/' + location;;return files;;gruntloadNpmTasks'grunt-css';gruntloadNpmTasks'grunt-css-urls';gruntregisterTask'release' 'cssUrls' 'cssmin' ;;
Based on the scenario described above, the url references will end up like this:
Copyright (c) 2012 Juan Pablo Garcia & Ideame Dev Team Licensed under the MIT license.