borodean / postcss-assets

An asset manager for PostCSS
MIT License
537 stars 32 forks source link

image-url() replication #51

Closed zslabs closed 8 years ago

zslabs commented 8 years ago

Hi, In Compass (within Middleman for example) there's a function called image-url() that allows users to specify an image and the system is able to determine not only the location, but also grab the respective "cache-busted" filename as well. So,

url('foo.png')

Would return:

url('/assets/images/foo-398ds09.png')

I didn't see this feature specifically called out in this plugin, but wanted to know if that is something that is available. Thanks!

borodean commented 8 years ago

@zslabs you can use cachebuster option when setting up the plugin:

assets({
  loadPaths: ["images", "fonts"],
  cachebuster: true
});

Then you’d get the cachebusted URL when you resolve() the asset:

/* This code... */
body { background: resolve("pattern.png"); }
/* ...becomes this: */
body { background: url("/images/pattern.png?15334c636b1") }

The default cachebusting is done by appending the hex-encoded modification date of a resolved asset as a query string. However, if you want to handle cachebusting some other way, you describe it by passing a function instead of true to the cachebuster option:

assets({
  cachebuster: function (filePath, urlPathname) {
    var hash = fs.statSync(filePath).mtime.getTime().toString(16);
    return {
      pathname: path.dirname(urlPathname)
        + '/' + path.basename(urlPathname, path.extname(urlPathname))
        + '-' + hash + path.extname(urlPathname)
    }
  }
});

The above example would allow to cachebust assets using the path:

/* This code... */
body { background: resolve("pattern.png"); }
/* ...now becomes this: */
body { background: url("/images/pattern-15334c636b1.png") }

For further info on how to use it check the cachebuster section of the README.

zslabs commented 8 years ago

Great, thanks!