Fork me on GitHub

Mincer - assets processor

Build Status

JavaScript port of Sprockets. It features same declarative dependency management (with exactly same language) for CSS and JavaScript and preprocessor pipeline. Mincer allows you to write assets in the languages like: CoffeeScript, LESS, Stylus.

See Sprockets and Mincer API Documentation for more details.

Installation

Install Mincer from npm registry:

$ npm install mincer

Or install bleeding edge version from GitHub repo:

$ npm install git://github.com/nodeca/mincer.git

Using Mincer from CLI

To use Mincer from CLI, you will need to intall it globally:

$ npm install mincer -g

Usage is really simple (see mincer -h for details):

$ mincer --include assets/javascripts \
         --include assets/stylesheets \
         --output public/assets \
         application.js application.css

If you are using mincer CLI often, you would probably want to "preset" some of the options/arguments for your project. Just create .mincerrc file and put argument you want in it. For example:

--include assets/javascripts --include assets/stylesheets --output public/assets

Understanding the Mincer Environment

You'll need an instance of the Mincer.Environment class to access and serve assets from your application.

The Environment has methods for retrieving and serving assets, manipulating the load path, and registering processors. It is also used by Mincer.Server which can be mounted directly as request event handler of http.Server or as connect middleware.

The Load Path

The load paths is an ordered list of directories that Mincer uses to search for assets.

In the simplest case, a Mincers environment's load path will consist of a single directory containing your application's asset source files. When mounted, server will serve assets from this directory as if they were static files in your public root.

The power of the load path is that it lets you organize your source files into multiple directories -- even directories that live outside your application -- and combine those directories into a single virtual filesystem. That means you can easily bundle JavaScript, CSS and images into a library and import them into your application.

Manipulating the Load Path

To add a directory to your environment's load path, use the appendPath and prependPath methods. Directories at the beginning of the load path have precedence over subsequent directories.

environment = new Mincer.Environment();
environment.appendPath('app/assets/javascripts');
environment.appendPath('lib/assets/javascripts');
environment.appendPath('vendor/assets/jquery');

In general, you should append to the path by default and reserve prepending for cases where you need to override existing assets.

Accessing Assets

Once you've set up your environment's load path, you can mount the environment as a server and request assets via HTTP. You can also access assets programmatically from within your application.

Logical Paths

Assets in Mincer are always referenced by their logical path.

The logical path is the path of the asset source file relative to its containing directory in the load path. For example, if your load path contains the directory app/assets/javascripts:

Asset source file Logical path
app/assets/javascripts/application.js application.js
app/assets/javascripts/models/project.js models/project.js

In this way, all directories in the load path are merged to create a virtual filesystem whose entries are logical paths.

Serving Assets Over HTTP

When you mount an environment, all of its assets are accessible as logical paths underneath the mount point. For example, if you mount your environment at /assets and request the URL /assets/application.js, Mincer will search your load path for the file named application.js and serve it.

var connect = require('connect');
var Mincer  = require('mincer');

var environment = new Mincer.Environment();
environment.appendPath('app/assets/javascripts');
environment.appendPath('app/assets/stylesheets');

var app = connect();
app.use('/assets', Mincer.createServer(environment));
app.use(function (req, res) {
  // your application here...
});

Accessing Assets Programmatically

You can use the findAsset method to retrieve an asset from a Mincers environment. Pass it a logical path and you'll get a BundledAsset instance back.

If it's first time you have requested asset you'll need to compile it. Call toString on the resulting asset to access its contents, length to get its length in bytes, mtime to query its last-modified time, and pathname to get its full path on the filesystem.

environment.findAsset('application.js').compile(function (err, asset) {
  asset.toString(); // resulting contents
  asset.length;     // length in bytes
  asset.mtime;      // last modified time
  asset.pathname;   // full path on the filesystem
});

NOTICE

In comparison to Sprockets, where assets is being compiled (rendered) the same time (in a synchronous fashion) it is initiated. In comparison we have compilation "delayed", that leads into the situation that real file digest is available for us ONLY after file was really compiled. Here's simple example of asset_path helper:

function asset_path(pathname) {
  var asset = environment.findAsset(pathname);
  return asset ? asset.digestPath : '';
}

The helper above works perfectly with static assets (those who have no processors assigned, e.g. images, fonts, etc.), but it will return you wrong digest path for application.js unless you compile it first:

var asset = environment.findAsset('application.js');

asset.digestPath; // uses initial digest (calculated against original source)

asset.compile(function (err, asset) {
  asset.digestPath; // correct digest path

  asset = environment.findAsset('application.js');
  asset.digestPath; // correct digest again, unless application.js was changed
});

Using Engines

Asset source files can be written in another language, like Stylus or CoffeeScript, and automatically compiled to CSS or JavaScript by Mincer. Compilers for these languages are called engines.

Engines are specified by additional extensions on the asset source filename. For example, a CSS file written in Stylus might have the name layout.css.styl, while a JavaScript file written in CoffeeScript might have the name dialog.js.coffee.

Styling with Stylus

Stylus is a revolutionary new language, providing an efficient, dynamic, and expressive way to generate CSS. Supporting both an indented syntax and regular CSS style.

If the stylus Node module is available to your application, you can use Stylus to write CSS assets in Mincer. Use the extension .css.styl.

Styling with LESS

LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions.

If the less Node module is available to your application, you can use LESS to write CSS assets in Mincer. Use the extension .css.less.

Scripting with CoffeeScript

CoffeeScript is a language that compiles to the "good parts" of JavaScript, featuring a cleaner syntax with array comprehensions, classes, and function binding.

If the coffee-script Node module is available to your application, you can use CoffeeScript to write JavaScript assets in Mincer. Use the extension .css.coffee.

Invoking JavaScript with EJS

Mincer provides an EJS engine for preprocessing assets using embedded JavaScript code. Append .ejs to a CSS or JavaScript asset's filename to enable the EJS engine.

You will need ejs Node module available to your application.

Note: Mincer processes multiple engine extensions in order from right to left, so you can use multiple engines with a single asset. For example, to have a CoffeeScript asset that is first preprocessed with EJS, use the extension .js.coffee.ejs.

JavaScript code embedded in an asset is evaluated in the context of a Mincer.Context instance for the given asset. Common uses for EJS include:

  • embedding another asset as a Base64-encoded data: URI with the asset_data_uri helper
  • inserting the URL to another asset, such as with the asset_path helper (you must register your own helper for this purpose, but it's dead simple).
  • embedding other application resources, such as a localized string database, in a JavaScript asset via JSON
  • embedding version constants loaded from another file

Using helpers

Mincer provides an easy way to add your own helpers for engines:

environment.registerHelper('version', function () {
  require(__dirname, '/package.json').version;
});

Now, you can call that helper with EJS like this:

var APP = window.APP = {version: '<%= version() %>'};

NOTICE Helpers currently work for EJS and Stylus only. So to use them with Less you will need to add EJS engine as well:

// file: foobar.less.ejs
.btn {
  background: url('<%= asset_path('bg.png') %>');
}

Managing and Bundling Dependencies

You can create asset bundles -- ordered concatenations of asset source files -- by specifying dependencies in a special comment syntax at the top of each source file.

Mincer reads these comments, called directives, and processes them to recursively build a dependency graph. When you request an asset with dependencies, the dependencies will be included in order at the top of the file.

The Directive Processor

Mincer runs the directive processor on each CSS and JavaScript source file. The directive processor scans for comment lines beginning with = in comment blocks at the top of the file.

//= require jquery
//= require jquery-ui
//= require backbone
//= require_tree .

The first word immediately following = specifies the directive name. Any words following the directive name are treated as arguments. Arguments may be placed in single or double quotes if they contain spaces, similar to commands in the Unix shell.

Note: Non-directive comment lines will be preserved in the final asset, but directive comments are stripped after processing. Mincer will not look for directives in comment blocks that occur after the first line of code.

Supported Comment Types

The directive processor understands comment blocks in three formats:

/* Multi-line comment blocks (CSS, Stylus, JavaScript)
 *= require foo
 */

// Single-line comment blocks (Stylus, JavaScript)
//= require foo

# Single-line comment blocks (CoffeeScript)
#= require foo

Mincer Directives

You can use the following directives to declare dependencies in asset source files.

For directives that take a path argument, you may specify either a logical path or a relative path. Relative paths begin with ./ and reference files relative to the location of the current file.

The require Directive

require path inserts the contents of the asset source file specified by path. If the file is required multiple times, it will appear in the bundle only once.

The include Directive

include path works like require, but inserts the contents of the specified source file even if it has already been included or required.

The require_directory Directive

require_directory path requires all source files of the same format in the directory specified by path. Files are required in alphabetical order.

The require_tree Directive

require_tree path works like require_directory, but operates recursively to require all files in all subdirectories of the directory specified by path.

The require_self Directive

require_self tells Mincer to insert the body of the current source file before any subsequent require or include directives.

The depend_on Directive

depend_on path declares a dependency on the given path without including it in the bundle. This is useful when you need to expire an asset's cache in response to a change in another file.

The stub Directive

stub path allows dependency to be excluded from the asset bundle. The path must be a valid asset and may or may not already be part of the bundle. Once stubbed, it is blacklisted and can't be brought back by any other require.

Credits

Great thanks to Sam Stephenson and Joshua Peek for the Sprockets, the most awesome and powerfull web assets processor I ever used, and which became a great source of inspiration (and model of almost all logic behind Mincer). Special thanks to Joshua for his assistance in hacking into Sprockets sources.

Author

Aleksey V Zapparov (follow @zapparov on twitter).

License

Copyright (c) 2012 Vitaly Puzrin

Released under the MIT license. See LICENSE for details.

class

Asset

internal

Description

The base class for BundledAsset, ProcessedAsset and StaticAsset.

Constructor

Class methods

constructor

Asset.new

    • new Asset(environment, logicalPath, pathname)
    • environment
      • Environment
    • logicalPath
      • String
    • pathname
      • String
class method

Asset.isDependencyFresh

    • Asset.isDependencyFresh(environment, dep)
      • Boolean
    • environment
      • Environment
      • Index
    • dep
      • Asset

Returns whenever given dep asset is fresh by checking it's mtime, and contents if it's match.

instance method

Asset#compile

    • Asset#compile([callback])
      • Void

Compiles asset and fires callback(err, asset) once it was compiled.

instance method

Asset#isFresh

    • Asset#isFresh(environment)
      • Boolean
    • environment
      • Environment
      • Index

Checks if Asset is fresh by comparing the actual mtime and digest to the inmemory model.

Used to test if cached models need to be rebuilt.

instance method

Asset#toArray

    • Asset#toArray()
      • Array

Expand asset into an Array of parts.

Appending all of an assets body parts together should give you the asset's contents as a whole.

instance method

Asset#toString

    • Asset#toString()
      • String
Alias of:
instance method

Asset#writeTo

    • Asset#writeTo(filename, options, callback, callback)
      • Void
    • filename
      • String
    • options
      • Object
    • callback
      • Function

Save asset to disk. Automatically gzip content if options.compress is true or filename matches *.gz pattern.

instance property

Asset#buffer

    • Asset#buffer
      • Buffer

Buffer content of asset.

instance property

Asset#dependencyPaths

internal
    • Asset#dependencyPaths
      • Array

String paths that are marked as dependencies after processing. Default to an empty Array.

instance property

Asset#digestPath

    • Asset#digestPath
      • String

Return logical path with digest spliced in.

"foo/bar-ce09b59f734f7f5641f2962a5cf94bd1.js"
instance property

Asset#isCompiled

    • Asset#isCompiled
      • Boolean

Reflects whenever asset is compiled or not.

instance property

Asset#requiredAssets

internal
    • Asset#requiredAssets
      • Array

ProcessedAssets that are required after processing. Default to an empty Array.

instance property

Asset#source

    • Asset#source
      • String

String (concatenated) content of asset.

Aliased as:
class

AssetAttributes

internal

Description

AssetAttributes is a wrapper similar to Rubie's Pathname that provides some helper accessors.

These methods should be considered internalish.

constructor

AssetAttributes.new

    • new AssetAttributes(environment, pathanme)
instance property

AssetAttributes#contentType

    • AssetAttributes#contentType
      • String

Returns the content type for the pathname. Falls back to application/octet-stream.

instance property

AssetAttributes#engineContentType

    • AssetAttributes#engineContentType
      • String

Returns implicit engine content type.

.coffee files carry an implicit application/javascript content type.

instance property

AssetAttributes#engineExtension

    • AssetAttributes#engineExtension
      • Array

Returns an Array of engine extensions.

"foo.js.coffee.ejs"
// -> [".coffee", ".ejs"]
instance property

AssetAttributes#engineFormatExtension

    • AssetAttributes#engineFormatExtension
      • String

Returns implicit engine extension.

.coffee files carry an implicit .js extension (due to it's implicit content type of application/javascript).

instance property

AssetAttributes#engines

    • AssetAttributes#engines
      • Array

Returns an array of engine classes.

instance property

AssetAttributes#extensions

    • AssetAttributes#extensions
      • Array

Returns Array of extension Strings.

"foo.js.coffee"
// -> [".js", ".coffee"]
instance property

AssetAttributes#formatExtension

    • AssetAttributes#formatExtension
      • String

Returns the format extension.

"foo.js.coffee"
// -> ".js"
instance property

AssetAttributes#logicalPath

    • AssetAttributes#logicalPath
      • String

Reverse guess logical path for fully expanded path.

This has some known issues. For an example if a file is shaddowed in the path, but is required relatively, its logical path will be incorrect.

instance property

AssetAttributes#processors

    • AssetAttributes#processors
      • Array

Returns all processors to run on the path.

instance property

AssetAttributes#searchPaths

    • AssetAttributes#searchPaths
      • Array

Returns paths search the load path for.

class

Base

internal

Description

Base class for Environment and Index.

INCLUDES

Constructor

Instance properties

constructor

Base.new

    • new Base()
instance method

Base#attributesFor

internal
    • pathname
      • String

Returns a AssetAttributes for pathname

instance method

Base#contentTypeOf

internal
    • Base#contentTypeOf(pathname)
      • String
    • pathname
      • String

Returns content type of pathname

instance method

Base#eachEntry

    • Base#eachEntry(root, iterator)
      • Void
    • root
      • String
    • iterator
      • Function

Calls iterator on each found file or directory in alphabetical order:

env.eachEntry('/some/path', function (entry) {
  console.log(entry);
});
// -> "/some/path/a"
// -> "/some/path/a/b.txt"
// -> "/some/path/a/c.txt"
// -> "/some/path/b.txt"
instance method

Base#eachFile

    • Base#eachFile(iterator)
      • Void
    • iterator
      • Function

Calls iterator for each file found within all registered paths.

instance method

Base#eachLogicalPath

    • Base#eachLogicalPath(filters, iterator)
      • Void
    • filters
      • Array
    • iterator
      • Function

Calls iterator on each found logical path (once per unique path) that matches at least one of the given filters.

Each filter might be a String, RegExp or a Function.

instance method

Base#entries

    • Base#entries(pathname)
      • Array
    • pathname
      • String

Proxy to Hike.Trail#entries. Works like fs.readdirSync. Subclasses may cache this method.

instance method

Base#findAsset

    • Base#findAsset(pathname[, options = {}])
    • pathname
      • String
    • options
      • Object

Find asset by logical path or expanded path.

instance method

Base#getFileDigest

    • Base#getFileDigest(pathname)
      • String
    • pathname
      • String

Read and compute digest of filename. Subclasses may cache this method.

instance method

Base#precompile

    • Base#precompile(files[, callback])
      • Void
    • files
      • Array
    • callback
      • Function

Helper to make sure that given list of files were compiled. Similar to compile, but does not write anything to disk.

environment.precompile(["app.js"], function (err, data) {
  //  data => {
  //    files: {
  //      "app.js" : "app-2e8e9a7c6b0aafa0c9bdeec90ea30213.js"
  //    },
  //    assets: {
  //      "app-2e8e9a7c6b0aafa0c9bdeec90ea30213.js" : {
  //        "logical_path"  : "app.js",
  //        "mtime"         : "2011-12-13T21:47:08-06:00",
  //        "digest"        : "2e8e9a7c6b0aafa0c9bdeec90ea30213"
  //      }
  //    }
  //  }
});

Needed when you want to render HTML with some JavaScript injected right into your page (e.g. single-page offline documentation) and your template engine does not support asynchronous helpers (e.g. Jade requires helpers to be synchronous).

instance method

Base#resolve

    • Base#resolve(logicalPath[, options = {}][, fn])
      • String
    • logicalPath
      • String
    • options
      • Object
    • fn
      • Function

Finds the expanded real path for a given logical path by searching the environment's paths.

env.resolve("application.js")
# => "/path/to/app/javascripts/application.js.coffee"

An Error with code = 'FileNotFound' is raised if the file does not exist.

instance method

Base#stat

    • Base#stat(pathname)
      • fs.Stats
    • pathname
      • String

Proxy to Hike.Trail#stat. Works like fs.statSync. Subclasses may cache this method.

instance property

Base#digest

    • Base#digest
      • crypto.Hash

Returns a crypto.Hash instance for the Environment.

This value serves two purposes. If two Environments have the same digest value they can be treated as equal. This is more useful for comparing environment states between processes rather than in the same. Two equal Environments can share the same cached assets.

The value also provides a seed digest for all Asset digests. Any change in the environment digest will affect all of its assets.

instance property

Base#digestAlgorithm

    • Base#digestAlgorithm
      • String

Digest algorithm: sha1 or md5. See Node manual on crypto module.

Default: md5.

instance property

Base#version

    • Base#version
      • String

Environment version.

environment.version = '2.0'
class

BundledAsset

internal

Description

BundledAssets are used for files that need to be processed and concatenated with other assets, e.g. .js and .css` files.

SUBCLASS OF

Asset

Constructor

Instance methods

Instance properties

constructor

BundledAsset.new

    • new BundledAsset()

See new for details.

instance method

BundledAsset#isFresh

    • BundledAsset#isFresh(environment)
      • Boolean
    • environment
      • Environment
      • Index

Checks if Asset is stale by comparing the actual mtime and digest to the inmemory model.

instance method

BundledAsset#toArray

    • BundledAsset#toArray()
      • Array

Return array of porcessed assets this asset contains of.

instance property

BundledAsset#dependencies

    • BundledAsset#dependencies
      • Array

Return an Array of Asset files that are declared dependencies.

class

CharsetNormalizer

Description

Some browsers have issues with stylesheets that contain multiple @charset definitions. The CharsetNormalizer processor strips out multiple @charset definitions.

The current implementation is naive. It picks the first @charset it sees and strips the others. This works for most people because the other definitions are usually UTF-8. A more sophisticated approach would be to re-encode stylesheets with mixed encodings.

This behavior can be disabled with:

environment.unregisterBundleProcessor('text/css', CharsetNormalizer);
SUBCLASS OF

Template

class

CoffeeEngine

Description

Engine for the CoffeeScript compiler. You will need coffee-script Node module installed in order to use Mincer with *.coffee files:

npm install coffee-script
SUBCLASS OF

Template

class method

CoffeeEngine.getOptions

    • CoffeeEngine.getOptions()
      • Object

Return options object.

class method

CoffeeEngine.setOptions

    • CoffeeEngine.setOptions(value)
      • Void
    • value
      • Object

Allows to set CoffeeScript compilation options. Default: {bare: true}.

Example
CoffeeScript.setOptions({bare: true});
class

Context

internal

Description

Context provides helper methods to all Template processors. They are typically accessed by EJS templates. You can mix in custom helpers by injecting them into ContextClass. Do not mix them into Context directly.

environment.registerHelper('asset_url', function () {
  // ...
});

// or in batch-mode
environment.registerHelper({
  asset_url: function () {
    // ...
  },
  // ...
});

<%= asset_url("foo.png") %>

The Context also collects dependencies declared by assets. See DirectiveProcessor for an example of this.

Constructor

Class methods

constructor

Context.new

    • new Context(environment, logicalPath, pathname)
    • environment
      • Environment
    • logicalPath
      • String
    • pathname
      • String
class method

Context.registerHelper

    • Context.registerHelper(name, func)
      • Void
    • Context.registerHelper(helpers)
      • Void
    • name
      • String
    • func
      • Function
    • helpers
      • Object

Register a helper that will be available in the engines that supports local helpers (e.g. EJS or Stylus). You should avoid registering helpers directly on Context class in favour of ContextClass (see registerHelper as well).

Example
Context.registerHelper('foo', foo_helper);
Context.registerHelper('bar', bar_helper);

// equals to

Context.registerHelper({
  foo: foo_helper,
  bar: bar_helper
});
instance method

Context#assetDataUri

    • Context#assetDataUri(pathname)
      • String

Returns a Base64-encoded data: URI with the contents of the asset at the specified path, and marks that path as a dependency of the current file.

Use assetDataUri from EJS with CSS or JavaScript assets:

#logo { background: url(<%= asset_data_uri('logo.png') %>) }

$('<img>').attr('src', '<%= asset_data_uri('avatar.jpg') %>')
instance method

Context#dependOn

    • Context#dependOn(pathname)
      • Void

Allows you to state a dependency on a file without including it.

This is used for caching purposes. Any changes made to the dependency file with invalidate the cache of the source file.

instance method

Context#dependOnAsset

    • Context#dependOnAsset(pathname)
      • Void

Allows you to state an asset dependency without including it.

This is used for caching purposes. Any changes that would invalidate the dependency asset will invalidate the source file. Unlike dependOn, this will include recursively the target asset's dependencies.

instance method

Context#evaluate

    • Context#evaluate(pathname, options = {}, callback)
      • Void
    • pathname
      • String
    • options
      • Object
    • callback
      • Function

Reads pathname and runs processors on the file.

instance method

Context#isAssetRequirable

    • Context#isAssetRequirable(pathname)
      • Boolean

Tests if target path is able to be safely required into the current concatenation.

instance method

Context#requireAsset

    • Context#requireAsset(pathname)
      • Void

require_asset declares path as a dependency of the file. The dependency will be inserted before the file and will only be included once.

If EJS processing is enabled, you can use it to dynamically require assets.

<%= requireAsset("#{framework}.js") %>
instance method

Context#resolve

    • Context#resolve(pathname[, options = {}][, fn])
      • String
    • pathname
      • String
    • options
      • Object
    • fn
      • Function

Given a logical path, resolve will find and return the fully expanded path. Relative paths will also be resolved. An optional contentType restriction can be supplied to restrict the search.

context.resolve("foo.js")
# => "/path/to/app/javascripts/foo.js"

context.resolve("./bar.js")
# => "/path/to/app/javascripts/bar.js"

context.resolve("foo", {contentType: 'application/javascript'})
# => "/path/to/app/javascripts/foo.js"

You may also provide an iterator function fn, that wil be passed to environments resolve when needed.

instance method

Context#stubAsset

    • Context#stubAsset(pathname)
      • Void

stubAsset blacklists pathname from being included in the bundle. pathname must be an asset which may or may not already be included in the bundle.

instance property

Context#contentType

    • Context#contentType
      • String

Returns content type of file

'application/javascript'
'text/css'
instance property

Context#logicalPath

    • Context#logicalPath
      • String

Returns logical path without any file extensions.

'app/javascripts/application.js'
# => 'app/javascripts/application'
instance property

Context#rootPath

    • Context#rootPath
      • String

Returns the environment path that contains the file.

If app/javascripts and app/stylesheets are in your path, and current file is app/javascripts/foo/bar.js, root_path would return app/javascripts.

instance property

Context#subclass

internal
    • Context#subclass
      • Function

Returns new subclass of Context.

class

DebugComments

Description

As we are using Node and most of renderers (like Stylus, Less and so on) are using callbacks and asynchronous approach really hard, it's nearly impossible to use original approach of of rendering not-bundled assets for development environment. So instead we use this post-processor to inject comments with pathname of the file in front of each bundled file.

This behavior can be disabled with:

environment.unregisterPostProcessor('text/css', DebugComments);
environment.unregisterPostProcessor('application/javascript', DebugComments);
SUBCLASS OF

Template

class

DirectiveProcessor

Description

The DirectiveProcessor is responsible for parsing and evaluating directive comments in a source file.

A directive comment starts with a comment prefix, followed by an "=", then the directive name, then any arguments.

  • JavaScript one-line comments: `//= require "foo"
  • CoffeeScript one-line comments: `#= require "baz"
  • JavaScript and CSS block comments: `*= require "bar"

This behavior can be disabled with:

environment.unregisterPreProcessor('text/css', DirectiveProcessor);
environment.unregisterPreProcessor('application/javascript', DirectiveProcessor);
SUBCLASS OF

Template

Instance methods

instance method

DirectiveProcessor#processDirectives

    • DirectiveProcessor#processDirectives(callback)
      • Void

Executes handlers for found directives.

See Also:
instance property

DirectiveProcessor#directives

    • DirectiveProcessor#directives
      • Array

Returns an Array of directive structures. Each structure is an Array with the line number as the first element, the directive name as the second element, third is an array of arguments.

[[1, "require", ["foo"]], [2, "require", ["bar"]]]
instance property

DirectiveProcessor#processedHeader

    • DirectiveProcessor#processedHeader
      • String

Returns the header String with any directives stripped.

instance property

DirectiveProcessor#processedSource

    • DirectiveProcessor#processedSource
      • String

Returns the source String with any directives stripped.

class

EjsEngine

Description

Engine for the EJS compiler. You will need ejs Node module installed in order to use Mincer with *.ejs files:

npm install ejs
SUBCLASS OF

Template

mixin

Engines

internal

Description

An internal mixin whose public methods are exposed on the Environment and Index classes.

An engine is a type of processor that is bound to an filename extension. application.js.coffee indicates that the CoffeeEngine engine will be ran on the file.

Extensions can be stacked and will be evaulated from right to left. application.js.coffee.ejs will first run EjsEngine then CoffeeEngine.

All Engines must follow the Template interface. It is recommended to subclass Template.

Its recommended that you register engine changes on your local Environment instance.

environment.registerEngine('.foo', FooProcessor);

The global registry is exposed for plugins to register themselves.

Mincer.registerEngine('.ejs', EjsEngine);

Instance methods

Instance properties

instance method

Engines#getEngins

    • Engines#getEngins(ext)
      • Object
      • Function

Returns an Object map of extension => Engines registered on the Environment. If an ext argument is supplied, the Engine register under that extension will be returned.

environment.getEngines()
// -> { ".styl": StylusEngine, ... }

environment.getEngines('.styl')
// -> StylusEngine
instance method

Engines#registerEngine

    • Engines#registerEngine(ext, klass)
      • Void

Registers a new Engine klass for ext. If the ext already has an engine registered, it will be overridden.

environment.registerEngine('.coffee', CoffeeScriptTemplate);
instance property

Engines#engineExtensions

    • Engines#engineExtensions
      • Array

Returns an Array of engine extension Strings.

environment.engineExtensions;
// -> ['.coffee', '.sass', ...]
class

Environment

Description

The heart of Mincer. Stores registered paths, engines, processors, etc.

SUBCLASS OF

Base

Constructor

Instance properties

constructor

Environment.new

    • new Environment(root)
instance method

Environment#expireIndex

internal
    • Environment#expireIndex()
      • Void

Reset assets internal cache.

instance method

Environment#findAsset

    • Environment#findAsset(path[, options])

Proxies call to findAsset of the one time index instance. findAsset automatically pushes cache here.

instance method

Environment#registerHelper

    • Environment#registerHelper(name, func)
      • Void
    • Environment#registerHelper(helpers)
      • Void

Proxy to registerHelper of current ContextClass.

Example
env.registerHelper('foo', function () {});

// shorthand syntax of

env.ContextClass.registerHelper('foo', function () {});
instance property

Environment#ContextClass

Copy of Context class, that is safe for any mutations. Use it to provide your own helpers.

See Also
instance property

Environment#index

Returns a cached version of the environment.

All its file system calls are cached which makes index much faster. This behavior is ideal in production since the file system only changes between deploys.

class

HamlCoffeeEngine

Description

Engine for the Haml Coffee Templat compiler. You will need haml-coffee Node module installed in order to use Mincer with *.hamlc files:

npm install haml-coffee
SUBCLASS OF

Template

class method

HamlCoffeeEngine.getNamespace

    • HamlCoffeeEngine.getNamespace()
      • String

Return compilation namespace.

class method

HamlCoffeeEngine.getOptions

    • HamlCoffeeEngine.getOptions()
      • Object

Return options object.

class method

HamlCoffeeEngine.setNamspace

    • HamlCoffeeEngine.setNamspace(value)
      • Void
    • value
      • String

Allows to set Haml Coffee Template compilation namespace. Default: 'HAML'.

Example
HamlCoffeeEngine.setNamspace('HAML_TPL');
class method

HamlCoffeeEngine.setOptions

    • HamlCoffeeEngine.setOptions(value)
      • Void
    • value
      • Object

Allows to set Haml Coffee Template compilation options. See Haml Coffee Template compilation options for details.

Default: {}.

Example
HamlCoffeeEngine.setOptions({basename: true});
class

Index

internal

Description

Index is a special cached version of Environment.

The expection is that all of its file system methods are cached for the instances lifetime. This makes Index much faster. This behavior is ideal in production environments where the file system is immutable.

Index should not be initialized directly. Instead use index.

SUBCLASS OF

Base

Class methods

Instance methods

Instance properties

class method

Index.getFileDigest

    • Index.getFileDigest(pathname)
      • crypto.Hash

Cached version of getFileDigest.

instance method

Index#expireIndex

internal
    • Index#expireIndex()
      • Void

Throws an error. Kept for keeping same interface as in Environment.

instance method

Index#findAsset

    • Index#findAsset(pathname[, options])

Caches calls to findAsset. Pushes cache to the upstream environment as well.

instance property

Index#index

Self-reference to provide same interface as in Environment.

class

LessEngine

Description

Engine for the Less compiler. You will need less Node module installed in order to use Mincer with *.less files:

npm install less
SUBCLASS OF

Template

class

Logger

Description

Provides unified logging interface for Mincer.

Logger.use({
  log: function (msg) {
    // my logging generic logic
  },
  debug: function (msg) {
    // logic for debug logging
  }
});
class method

Logger.debug

    • Logger.debug(message)
      • Void

Used for any non-critical information, that might be useful mostly for development only.

class method

Logger.error

    • Logger.error(message)
      • Void

Used for logging errors.

class method

Logger.info

    • Logger.info(message)
      • Void

Used for important messages.

class method

Logger.log

    • Logger.log(level, message)
      • Void

Generic logging method. Used as last resort if backend logger (provided to use) have no method for requested level.

class method

Logger.use

    • Logger.use(logger)
      • Void
    • logger
      • Object
    • An object that respond to some (or all) log levels

Allows to provide you own logging backend (by default all log messages are going to "nowhere").

Log levels

Your logger backend should normally respond to following methods:

  • logger.log(level, message) : Used by log
  • logger.debug(message) : Used by debug
  • logger.info(message) : Used by info
  • logger.warn(message) : Used by warn
  • logger.error(message) : Used by error
Example
Logger.use(console);
class method

Logger.warn

    • Logger.warn(message)
      • Void

Used for very important messages (e.g. notification about ongoing FS changes etc).

class

Manifest

Description

The Manifest logs the contents of assets compiled to a single directory. It records basic attributes about the asset for fast lookup without having to compile. A pointer from each logical path indicates with fingerprinted asset is the current one.

The JSON is part of the public API and should be considered stable. This should make it easy to read from other programming languages and processes that don't have sprockets loaded. See #assets and #files for more infomation about the structure.

Constructor

Instance methods

Instance properties

constructor

Manifest.new

    • new Manifest(environment, path)

Create new Manifest associated with an environment. path is a full path to the manifest json file. The file may or may not already exist. The dirname of the path will be used to write compiled assets to. Otherwise, if the path is a directory, the filename will default to "manifest.json" in that directory.

new Manifest(environment, "./public/assets/manifest.json");
instance method

Manifest#compile

    • Manifest#compile(files[, callback])
      • Void
    • files
      • Array
    • callback
      • Function

Compile and write asset(s) to directory. The asset is written to a fingerprinted filename like app-2e8e9a7c6b0aafa0c9bdeec90ea30213.js. An entry is also inserted into the manifest file.

manifest.compile(["app.js"], function (err, data) {
  //  data => {
  //    files: {
  //      "app.js" : "app-2e8e9a7c6b0aafa0c9bdeec90ea30213.js",
  //      ...
  //    },
  //    assets: {
  //      "app-2e8e9a7c6b0aafa0c9bdeec90ea30213.js" : {
  //        "logical_path"  : "app.js",
  //        "mtime"         : "2011-12-13T21:47:08-06:00",
  //        "digest"        : "2e8e9a7c6b0aafa0c9bdeec90ea30213"
  //      },
  //      ...
  //    }
  //  }
});
instance property

Manifest#assets

    • Manifest#assets
      • Object

Returns internal assets mapping. Keys are logical paths which map to the latest fingerprinted filename.

Synopsis:
Logical path (String): Fingerprint path (String)
Example:
{
  "application.js" : "application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js",
  "jquery.js"      : "jquery-ae0908555a245f8266f77df5a8edca2e.js"
}
instance property

Manifest#files

    • Manifest#files
      • Object

Returns internal file directory listing. Keys are filenames which map to an attributes array.

Synopsis:
Fingerprint path (String):
  logical_path: Logical path (String)
  mtime: ISO8601 mtime (String)
  digest: Base64 hex digest (String)
Example:

{ "application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js" : { 'logical_path' : "application.js", 'mtime' : "2011-12-13T21:47:08-06:00", 'digest' : "2e8e9a7c6b0aafa0c9bdeec90ea30213" } }

mixin

Mime

internal

Description

An internal mixin whose public methods are exposed on the Environment and Index classes.

Provides helpers to deal with mime types.

Instance properties

instance method

Mime#getExtensionForMimeType

    • Mime#getExtensionForMimeType(type)
      • String

Returns extension for mime type.

instance method

Mime#getMimeType

    • Mime#getMimeType(ext)
      • String

Returns the mime type for the extension.

instance method

Mime#registerMimeType

    • Mime#registerMimeType(type, ext)
      • Void

Register new mime type.

instance property

Mime#registeredMimeTypes

    • Mime#registeredMimeTypes
      • Mimoza

Returns a copy of Mimoza instance with explicitly registered mime types.

namespace

Mincer

Description

This is a main entry point of the module (an object that you get by calling require('mincer'). You can get acces to some of the internal classes using this object.

var env = new (require('mincer').Environment)(__dirname);

Mincer depends on some 3rd-party modules. Most valueble (for understanding an API) are:

EXTENDED BY

Class methods

class method

Mincer.createServer

    • Mincer.createServer(environment[, manifest])
      • Function
class property

Mincer.CharsetNormalizer

class property

Mincer.CoffeeEngine

class property

Mincer.DebugComments

class property

Mincer.DirectiveProcessor

class property

Mincer.EjsEngine

class property

Mincer.Environment

class property

Mincer.HamlCoffeeEngine

class property

Mincer.LessEngine

class property

Mincer.logger

read-only
class property

Mincer.Manifest

class property

Mincer.SafetyColons

class property

Mincer.Server

class property

Mincer.StylusEngine

class property

Mincer.Template

class property

Mincer.VERSION

read-only
    • Mincer.VERSION
      • String
mixin

Paths

internal

Description

An internal mixin whose public methods are exposed on the Environment and Index classes.

Provides helpers to work with Hike.Trail instance.

Instance properties

instance method

Paths#appendPath

    • Paths#appendPath(path)
      • Void

Append a path to the paths list. Paths at the beginning have a higher priority.

instance method

Paths#clearPaths

    • Paths#clearPaths()
      • Void

Clear all paths and start fresh.

There is no mechanism for reordering paths, so its best to completely wipe the paths list and reappend them in the order you want.

instance method

Paths#prependPath

    • Paths#prependPath(path)
      • Void

Prepend a path to the paths list. Paths at the end have the least priority.

instance property

Paths#extensions

    • Paths#extensions
      • Array

Returns an Array of extensions.

These extensions maybe omitted from logical path searches.

[".js", ".css", ".coffee", ".sass", ...]
instance property

Paths#paths

    • Paths#paths
      • Array

Returns an Array of path Strings.

These paths will be used for asset logical path lookups.

Note that a copy of the Array is returned so mutating will have no affect on the environment. See appendPath, prependPath, and clearPaths.

instance property

Paths#root

    • Paths#root
      • String

Returns Environment root.

All relative paths are expanded with root as its base. To be useful set this to your applications root directory.

class

ProcessedAsset

internal

Description

ProcessedAssets are internal representation of processable files.

SUBCLASS OF

Asset

Instance methods

constructor

ProcessedAsset.new

    • new ProcessedAsset()

See new for details.

instance method

ProcessedAsset#isFresh

    • ProcessedAsset#isFresh(environment)
      • Boolean
    • environment
      • Environment
      • Index

Checks if Asset is stale by comparing the actual mtime and digest to the inmemory model.

mixin

Processing

internal

Description

An internal mixin whose public methods are exposed on the Environment and Index classes.

instance method

Processing#addEngineToTrail

internal
    • Processing#addEngineToTrail(ext, klass)
      • Void

Registers extension (and corresponding aliases) for given klass in the trail.

instance method

Processing#getBundleProcessors

    • Processing#getBundleProcessors(mimeType = null)
      • Array
      • Types.Hash

Returns an Array of Processor classes. If a mimeType argument is supplied, the processors registered under that extension will be returned.

Bundle Processors are ran on concatenated assets rather than individual files.

All Processors must follow the Template interface. It is recommended to subclass Template.

instance method

Processing#getPostProcessors

    • Processing#getPostProcessors(mimeType = null)
      • Array
      • Types.Hash

Returns an Array of Processor classes. If a mime_type argument is supplied, the processors registered under that extension will be returned.

Postprocessors are ran after Preprocessors and Engine processors.

instance method

Processing#getPreProcessors

    • Processing#getPreProcessors(mimeType = null)
      • Array
      • Types.Hash

Returns an Array of Processor classes. If a mime_type argument is supplied, the processors registered under that extension will be returned.

Preprocessors are ran before Postprocessors and Engine processors.

instance method

Processing#registerBundleProcessor

    • Processing#registerBundleProcessor(mimeType, klass[, fn])
      • Void

Registers a new BundleProcessor klass for mime_type.

registerBundleProcessor('text/css', CharsetNormalizer);

A function can be passed for to create a shorthand processor.

registerBundleProcessor('text/css', 'my_processor', function (context, data, callback) {
  callback(null, data.replace(...));
});
instance method

Processing#registerPostProcessor

    • Processing#registerPostProcessor(mimeType, klass[, fn])
      • Void

Registers a new Postprocessor klass for mime_type.

registerPostprocessor('text/css', DirectiveProcessor);

A function can be passed for to create a shorthand processor.

registerPostprocessor('text/css', 'my_processor', function (context, data, callback) {
  callback(null, data.replace(...));
});
instance method

Processing#registerPreProcessor

    • Processing#registerPreProcessor(mimeType, klass[, fn])
      • Void

Registers a new preprocessor klass for mime_type.

registerPreprocessor('text/css', DirectiveProcessor);

A function can be passed for to create a shorthand processor.

registerPreProcessor('text/css', 'my_processor', function (context, data, callback) {
  callback(null, data.replace(...));
});
instance method

Processing#unregisterBundleProcessor

    • Processing#unregisterBundleProcessor(mimeType, klass)
      • Void

Remove BundleProcessor klass for mime_type.

unregisterBundleProcessor('text/css', CharsetNormalizer);
instance method

Processing#unregisterPostProcessor

    • Processing#unregisterPostProcessor(mimeType, klass)
      • Void

Remove Postprocessor klass for mime_type.

unregisterPostprocessor('text/css', DirectiveProcessor);
instance method

Processing#unregisterPreProcessor

    • Processing#unregisterPreProcessor(mimeType, klass)
      • Void

Remove Preprocessor klass for mime_type.

unregisterPreprocessor('text/css', DirectiveProcessor);
instance property

Processing#cssCompressor

CSS compression function.

This is a magical property, when you assign your function, it automagically creates an instance of Processor with provided function as internal worker. The function you provide expected to have follwoing signature:

env.cssCompressor = function (context, data, callback) {
  // ... do something with data then fire callback with result
  callback(err, result);
};

But, getting the value of this property will return a subclass of Processor.

instance property

Processing#formatExtension

    • Processing#formatExtension
      • Array

Returns an Array of format extension Strings.

// => ['.js', '.css']
instance property

Processing#jsCompressor

JavaScript compression function.

This is a magical property, when you assign your function, it automagically creates an instance of Processor with provided function as internal worker. The function you provide expected to have follwoing signature:

env.jsCompressor = function (context, data, callback) {
  // ... do something with data then fire callback with result
  callback(err, result);
};

But, getting the value of this property will return a subclass of Processor.

class

Processor

internal

Description

Used to create custom processors without need to extend Template by simply providing a function to the processor registration methods:

var name = 'my-pre-processor';
var func = function (context, data, callback) {
  callback(null, data.toLowerCase());
};

// register custom pre-processor
environment.registerPreProcessor('text/css', name, func);

// unregister custom pre-processor
environment.unregisterPreProcessor('text/css', name);
See Also:
SUBCLASS OF

Template

Class methods

class method

Processor.create

    • Processor.create(name, func)
      • Function

Returns new Processor subclass.

class

SafetyColons

Description

For JS developers who are colonfobic, concatenating JS files using the module pattern usually leads to syntax errors.

The SafetyColons processor will insert missing semicolons to the end of the file.

This behavior can be disabled with:

environment.unregisterPostProcessor('application/javascript', SafetyColons);
SUBCLASS OF

Template

class

Server

Description

Easy to use server/middleware ideal for serving assets your assets:

  • great for development, as it recompiles canged assets on-fly
  • great for production, as it caches results, and it can become as effecient as staticCache middleware (or even better) of connect module.
Examples
// development mode
var srv = new Server(env);

// production mode
var srv = new Server(env.index);

// production mode (restrictive)
var files = ['app.js', 'app.css', 'logo.jpg'];
manifest.compile(files, function (err, manifestData) {
  var srv = new Server(env.index, manifestData);
});

You can use this server in your connect app (or as request listener of http server) like this:

app.use(function (req, res) {
  srv.handle(req, res);
});

// there's a shorthand syntax as well:

app.use(mincer.createServer(env));

Constructor

Class methods

Instance methods

constructor

Server.new

    • new Server(environment[, manifest])
    • environment
      • Environment
      • Index
    • manifest
      • Object
    • Data returned by compile

If you provide manifest, then server will not even try to find files on FS unless they are specified in the manifest.

class method

Server.createServer

    • Server.createServer(environment[, manifest])
      • Function
    • environment
      • Environment
    • manifest
      • Object

Returns a server function suitable to be used as request event handler of http Node library module or as connect middleware.

Example
// Using TJ's Connect module
var app = connect();
app.use('/assets/', Server.createServer(env));
See Also
instance method

Server#compile

    • Server#compile(pathname, bundle, callback(err, asset))
      • Void
    • pathname
      • String
    • bundle
      • Boolean
    • callback
      • Function

Finds and compiles given asset.

instance method

Server#handle

    • Server#handle(req, res)
      • Void
    • req
      • http.ServerRequest
    • res
      • hhtp.ServerResponse

Hander function suitable for usage as server request event listenet or as middleware for TJ's connect module.

Exampple

var assetsSet

instance method

Server#log

internal
    • Server#log(level, event)
      • Void
    • level
      • String
    • Event level

    • event
      • Object
    • Event data

This is an internal method that formats and writes messages using logger and it fits almost 99% of cases. But if you want to integrate this Server into your existing application and have logs formatted in your way you can override this method.

Event

Event is an bject with following fields:

  • code (Number): Status code
  • message (String): Message
  • elapsed (Number): Time elapsed in milliseconds
  • url (String): Request url. See http.request.url.
  • method (String): Request method. See http.request.method.
  • headers (Object): Request headers. See http.request.headers.
  • httpVersion (String): Request httpVersion. See http.request.httpVersion.
class

StaticAsset

internal

Description

Represents static asset the one that has no any processors associated with.

SUBCLASS OF

Asset

Constructor

constructor

StaticAsset.new

    • new StaticAsset()

See new for details.

class

StylusEngine

Description

Engine for the Stylus compiler. You will need stylus Node module installed in order to use Mincer with *.stylus files:

npm install stylus
SUBCLASS OF

Template

Class properties

class method

StylusEngine.clearConfigurators

    • StylusEngine.clearConfigurators()
      • Void

Remove all registered configurators.

class method

StylusEngine.registerConfigurator

    • StylusEngine.registerConfigurator(fn)
      • Void
    • fn
      • Function

Append function, that will be running everytime engine will run renderer.

var nib = require('nib');

Stylus.registerConfigurator(function (style) {
  style.use(nib());
});
class property

StylusEngine.configurators

    • StylusEngine.configurators
      • Array

Copy of registered configurators.

class

Template

Description

Template provides a base class for engines and processors. Think of it as of Ruby's Tilt::Template class, that provides unified interface for template renderers.

Example
// Create subclass
function MyProcessor() { Template.apply(this, arguments); }
require('util').inherits(MyProcessor, Template);

// Define evaluate method
MyProcessor.prototype.evaluate(context, locals, callback) {
  var data = this.data.toLowerCase();
  callback(null, data);
};

Constructor

constructor

Template.new

    • new Template(file[, reader])
    • file
      • String
    • reader
      • Function

Creates new instance of template and fills it with some base properties.

instance method

Template#evaluate

    • Template#evaluate(context, locals, callback)
      • Void
    • context
      • Context
    • locals
      • Object
    • callback
      • Function

Real renderer function.

You MUST redefine this method in your template. By default this method is throws an Error that it's not implemented.

Example
MyProcessor.prototype.evaluate = function (context, locals, callback) {
  var data = this.data.replace(this.secret, '***TOP-SECRET***');
  callback(null, data);
};
instance method

Template#initializeEngine

    • Template#initializeEngine()
      • Void

Initializes engine, if it's not yet initialized.

You MAY redefine this method in your template if you are using engine initialization. Default implementation does nothing.

Example
var backend; // lazy-load is so lazy
MyProcessor.prototype.initializeEngine = function () {
  backend = require('my-secret-module');
};
See Also
instance method

Template#isInitialized

    • Template#isInitialized()
      • Boolean

Test whenever template engine/processor was already initialized or not.

You MAY redefine this method in your template if you are using engine initialization. Default implementation always returns true.

Example
var backend; // lazy-load is so lazy
MyProcessor.prototype.isInitialized = function () {
  return !!backend;
};
See Also
instance method

Template#require

    • Template#require(name)
      • Mixed
    • name
      • String

Wrapper over native require() method, that produces beautified errors.

Used for engines and processors which depends on 3rd-party modules (e.g. StylusEngine needs stylus module). Once such engine initialized (if associated file is being processed) and required module not found this will rethrow Error with some clarification why error happened.