usemin

ekryski edited this page Nov 13, 2012 · 5 revisions

» Home

» Tasks


» clean: Wipe the previous build dirs.

» mkdirs: Prepares the build dirs.

» concat: Concatenate files. (built-in)

» css: Concats, replaces @imports and minifies CSS files.

» min: Minify files using UglifyJS (built-in)

» rev: Automate the revving of assets and perform the hash rename

» usemin: Replaces references to non-minified scripts / stylesheets


» serve: Spawns up a basic local http server

» connect: livereload version of serve task

Clone this wiki locally

Task - usemin

Replaces references to non-optimized scripts / stylesheets into a set of html files (or any template / views) and CSS files.

Usemin task is probably the trickiest one. It'll replace references to non minified scripts / stylesheets to their optimized / versioned equivalent.

usemin: {
  html: ['**/*.html', '**/*.mustache', '**/*.hbs', '..'],
  css: '**/*.css'
}

In this configuration, it'll handle the replacement for any HTML and CSS files below the application directory.

Right now the replacement is based on the filename parsed from content and the files present in according directory (eg. looking up matching revved filename into output/ dir to figure out the hash generated).

If you'd like a little bit more flexibility, you can use "directives", some special kind of html comments surrounding the part of html we want to replace (original idea from @necolas in: #831)

There is no need for JSDOM for this, this is plain regexp (JSDOM required for data-build attributes).

Ex:

<!-- build:css css/site.css -->
<link rel="stylesheet" href="css/style.css">
<!-- endbuild -->

Results in:

<link rel="stylesheet" href="css/site.css">

So you should make sure that css/site.css match your Gruntfile configuration for the CSS optimization task, same goes for JS files.

A directive is composed of the following part:

<!-- build:<target> <output> -->
... block ...
<!-- endbuild -->
  • <target> A known target is required (css or js). It'll namely allow you to replace the html "block" with appropriate tag (eg. a <link> for stylesheets, a <script> for js files, the task won't guess this from markup for you)

  • <output> Path to the optimized asset. The html "block" is replaced with according tag (depending on <target>) while replacing the src or href attribute with the <output> value.

  • ... block ... Anything inside the <!-- build.. --> and <!-- endbuild --> is replaced depending on <target> and <output> values.

The resulting html is then passed through the global replace, looking up matching revved filename in the output directory (defaults to publish/), replacing references to their hash-prepended version.

This "directives" system will provide you a nice level of flexibility, and the ability to be very descriptive on what gets replaced and by what.