Created
September 21, 2012 23:00
-
-
Save arikon/3764401 to your computer and use it in GitHub Desktop.
Stylus plugin to resolve relative paths to images on @import
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
var S = require('stylus'), | |
FS = require('fs'), | |
URL = require('url'), | |
PATH = require('path'); | |
var path = PATH.resolve('bundle.styl'); | |
S(FS.readFileSync(path, 'utf8')) | |
.set('filename', path) | |
.define('url', url()) | |
.render(function(err, css){ | |
if (err) throw err; | |
console.log(css); | |
}); | |
/** | |
* Url processing function. | |
* | |
* Translates relative urls to images and so on to the urls | |
* relative to the root file. | |
* | |
* Limitations: | |
* - could not translate paths in `@css` litarals | |
* - could not translate paths of `@import *.css` literals | |
*/ | |
function url() { | |
function fn(url) { | |
// Compile the url | |
var compiler = new S.Compiler(url); | |
compiler.isURL = true; | |
url = url.nodes.map(function(node){ | |
return compiler.visit(node); | |
}).join(''); | |
// Parse literal | |
url = URL.parse(url); | |
// Absolute with protocol | |
if (url.protocol) return urlLiteral(url.href); | |
// TODO: absolute without protocol | |
// Relative | |
var stack = this.importStack, | |
dir = PATH.dirname(this.filename), | |
abs = PATH.resolve(dir, PATH.dirname(stack[stack.length - 1]), url.href), | |
rel = PATH.relative(dir, abs); | |
return urlLiteral(rel); | |
}; | |
fn.raw = true; | |
return fn; | |
} | |
function urlLiteral(url) { | |
return new S.nodes.Literal('url("' + url + '")'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment