diff --git a/lib/index.js b/lib/index.js index 14776f8..205ab73 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,5 +1,6 @@ var Assets = require('assets'); -var dirname = require('path').dirname; +var p = require('path'); +var dirname = p.dirname; var functions = require('postcss-functions'); var postcss = require('postcss'); var quote = require('./quote'); @@ -23,6 +24,15 @@ function formatHeight(measurements) { return util.format('%dpx', measurements.height); } +// Normalize css assets path, resolve to project base if start with '/' +function normalizePath(path, options) { + var normalizedPath = unquote(unescapeCss(path)); + if (normalizedPath.charAt(0) === '/') { + normalizedPath = p.resolve(options.basePath || '.', normalizedPath.slice(1)); + } + return normalizedPath; +} + function plugin(options) { var params = options || {}; var resolver; @@ -46,6 +56,10 @@ function plugin(options) { }); } + function resolveUrl(path) { + return resolver.url(normalizePath(path, resolver.options)).then(formatUrl); + } + return postcss() .use(function appendInputDir(css) { var inputDir; @@ -67,24 +81,22 @@ function plugin(options) { }) .use(functions({ functions: { - resolve: function resolve(path) { - var normalizedPath = unquote(unescapeCss(path)); - return resolver.url(normalizedPath).then(formatUrl); - }, + url: resolveUrl, + resolve: resolveUrl, inline: function inline(path) { - var normalizedPath = unquote(unescapeCss(path)); + var normalizedPath = normalizePath(path, resolver.options); return resolver.data(normalizedPath).then(formatUrl); }, size: function size(path, density) { - var normalizedPath = unquote(unescapeCss(path)); + var normalizedPath = normalizePath(path, resolver.options); return measure(normalizedPath, density).then(formatSize); }, width: function width(path, density) { - var normalizedPath = unquote(unescapeCss(path)); + var normalizedPath = normalizePath(path, resolver.options); return measure(normalizedPath, density).then(formatWidth); }, height: function height(path, density) { - var normalizedPath = unquote(unescapeCss(path)); + var normalizedPath = normalizePath(path, resolver.options); return measure(normalizedPath, density).then(formatHeight); } }