Fork me on GitHub

Mincer - assets processor

Build Status NPM version

JavaScript port of Sprockets (v2.10.0). 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 and others. Moreover mincer has advanced built-in features, not available in sprockets:

  • sourcemaps support
  • macros support (nice alternative to EJS)

See Sprockets, Mincer API Documentation and Mincer examples for more details.

Supported engines are described in Wiki. If you wish to add new engine support - read tutorial. Also you can search existing extensions in npm.

Notice on upgrade to 1.4.x

If your project is using autoprefixer or csswring processors:

  • upgrade csswring to >=4.x and autoprefixer to >= 6.x
    • if you used legacy autoprefixer-core package, replace it with autoprefixer
  • include postcss >= 4.1

Installation

Install Mincer from npm registry:

$ npm install mincer

Using Mincer from CLI

To use Mincer from CLI, you will need to install 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:

<table> <tr> <th>Asset source file</th> <th>Logical path</th> </tr> <tr> <td>app/assets/javascripts/application.js</td> <td>application.js</td> </tr> <tr> <td>app/assets/javascripts/models/project.js</td> <td>models/project.js</td> </tr> </table>

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.

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.

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

asset.toString(); // resulting contents
asset.length;     // length in bytes
asset.mtime;      // last modified time
asset.pathname;   // full path on the filesystem

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.

Styling with Sass

Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more.

If the node-sass Node module is available to your application, you can use Sass to write CSS assets in Mincer. Use the extension .css.sass or .css.scss.

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 .js.coffee.

JavaScript Templating with Jade

Mincer supports JavaScript templates for client-side rendering of strings or markup. JavaScript templates have the special format extension .jst and are compiled to JavaScript functions.

When loaded, a JavaScript template function can be accessed by its logical path as a property on the global JST object. Invoke a template function to render the template as a string. The resulting string can then be inserted into the DOM.

// templates/hello.jst.jade
div Hello, #{ name }!
// application.js
//= require templates/hello
$("#hello").html(JST["templates/hello"]({ name: "Sam" }));

Mincer supports one template languages: Jade.

If jade Node module is available to your application, you can use Jade templates in Mincer. Jade templates have the extension .jst.jade. To use compiled templates you will need to require Jade runtime before calling renderer functions.

Invoking JavaScript with EJS

Note see macros description for more convenient alternative.

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 () {
  var path = require('path');
  return require( path.join(__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') %>');
}

Macros

This feature is designed as simple alternative to EJS, that does not requires additional extention and does not break language syntax. When enabled, any '$$ expression $$' or "$$ expression $$" pattern will be replaced with evaluated expression value. In expression you can write JS code and use registered helpers. Macros are off by default. You should enable those for particular extensions:

Mincer.MacroProcessor.configure(['.js', '.css']);

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.

Asset

internal

Description

The base class for BundledAsset, ProcessedAsset and StaticAsset.

Constructor

Class methods

Instance methods

Asset.new

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

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.

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.

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.

Asset#toString

    • Asset#toString()
      • String
Alias of:

Asset#buffer

    • Asset#buffer
      • Buffer

Buffer content of asset.

Asset#dependencyPaths

internal
    • Asset#dependencyPaths
      • Array

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

Asset#digestPath

    • Asset#digestPath
      • String

Return logical path with digest spliced in.

"foo/bar-ce09b59f734f7f5641f2962a5cf94bd1.js"

Asset#relativePath

    • Asset#relativePath
      • String

Returns AssetAttributes#relativePath of current file.

Asset#requiredAssets

internal
    • Asset#requiredAssets
      • Array

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

Asset#source

    • Asset#source
      • String

String (concatenated) content of asset.

Aliased as:

AssetAttributes

internal

Description

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

These methods should be considered internalish.

AssetAttributes.new

    • new AssetAttributes(environment, pathanme)

AssetAttributes#contentType

    • AssetAttributes#contentType
      • String

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

AssetAttributes#engineContentType

    • AssetAttributes#engineContentType
      • String

Returns implicit engine content type.

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

AssetAttributes#engineExtension

    • AssetAttributes#engineExtension
      • Array

Returns an Array of engine extensions.

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

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).

AssetAttributes#engines

    • AssetAttributes#engines
      • Array

Returns an array of engine classes.

AssetAttributes#extensions

    • AssetAttributes#extensions
      • Array

Returns Array of extension Strings.

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

AssetAttributes#formatExtension

    • AssetAttributes#formatExtension
      • String

Returns the format extension.

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

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.

AssetAttributes#processors

    • AssetAttributes#processors
      • Array

Returns all processors to run on the path.

AssetAttributes#relativePath

    • AssetAttributes#relativePath
      • String

Returns full path name relative to environment's root.

AssetAttributes#searchPaths

    • AssetAttributes#searchPaths
      • Array

Returns paths search the load path for.

Autoprefixer

Description

Post processor that runs autoprefixer for css. You will need autoprefixer and postcss Node modules installed:

npm install autoprefixer
npm install postcss
SUBCLASS OF

Template

Class methods

Autoprefixer.configure

    • Autoprefixer.configure(reqs)
      • Void
    • reqs
      • Array
      • String

Allows to set Autoprefixer requirements.

Default: undefined.

Example
Autoprefixer.configure(['> 1%', 'ie 8']);

Base

internal

Description

Base class for Environment and Index.

INCLUDES

Constructor

Base.new

    • new Base()

Base#attributesFor

internal
    • pathname
      • String

Returns a AssetAttributes for pathname

Base#contentTypeOf

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

Returns content type of pathname

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"

Base#eachFile

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

Calls iterator for each file found within all registered paths.

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.

Base#entries

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

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

Base#findAsset

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

Find asset by logical path or expanded path.

Base#getFileDigest

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

Read and compute digest of filename. Subclasses may cache this 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.

Base#stat

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

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

Base#cache

    • Base#cache
      • Mixed

Cache backend.

Default: null.

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.

Base#digestAlgorithm

    • Base#digestAlgorithm
      • String

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

Default: md5.

Base#version

    • Base#version
      • String

Environment version.

environment.version = '2.0'

BundledAsset

internal

Description

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

SUBCLASS OF

Asset

Constructor

Instance methods

Instance properties

BundledAsset.new

    • new BundledAsset()

See new Asset for details.

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.

BundledAsset#toArray

    • BundledAsset#toArray()
      • Array

Return array of porcessed assets this asset contains of.

BundledAsset#dependencies

    • BundledAsset#dependencies
      • Array

Return an Array of Asset files that are declared dependencies.

Caching

internal

Description

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

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

CoffeeEngine

Description

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

npm install coffee-script
SUBCLASS OF

Template

Class methods

CoffeeEngine.configure

    • CoffeeEngine.configure(opts)
      • Void
    • opts
      • Object

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

Example
CoffeeScript.configure({bare: true});

Compressing

internal

Description

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

Instance properties

Compressing#getCompressors

    • Compressing#getCompressors()
      • Object

Returns compressors groupped by mime-type.

Compressing#registerCompressor

    • Compressing#registerCompressor(mimeType, name, klass)
      • Void

Registers a compressor klass as name for mimeType.

environment.registerCompressor('text/css', 'sass', SassCompressor);

Compressing#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) {
  var compressed_data;
  // ... do something with data...
  return compressed_data;
};

Also you can use predifined CSS compressor [CssoCompressor] by passing it's identifier as a string:

env.cssCompressor = 'csso';

Throws Error if compressor is not a function or not registered one.

Compressing#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) {
  var compressed_data;
  // ... do something with data...
  return compressed_data;
};

Also you can use predifined JS compressor [UglifyCompressor] by passing it's identifier as a string:

env.jsCompressor = 'uglify';

Throws Error if compressor is not a function or not registered one.

Configuring

internal

Description

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

Configuring#disable

    • Configuring#disable(name)
      • Void

Disable configuration.

Example
env.disable('autoprefixer');

Configuring#enable

    • Configuring#enable(name)
      • Void

Enable configuration.

Example
env.enable('autoprefixer');

Configuring#getConfigurations

    • Configuring#getConfigurations()
      • Object

Returns copy of registered configurations.

Configuring#isEnabled

    • Configuring#isEnabled(name)
      • Void

Tells whenever given configuration enabled or not.

Example
if (env.isEnabled('source_maps')) {
  // ...
}

Configuring#registerConfiguration

    • Configuring#registerConfiguration(name, options)
      • Void
Example
Mincer.registerConfiguration('autoprefixer', {
  enable: function (self) {
    self.registerPostProcessor('text/css', Mincer.Autoprefixer);
  },
  disable: function (self) {
    self.unregisterPostProcessor('text/css', Mincer.Autoprefixer);
  }
});

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 Environment#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

Context.new

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

Context.defineAssetPath

    • Context.defineAssetPath(func)
      • Void

Syntax sugar that provides an easy way to set real implementation of assetPath and propose it to helpers.

Example:
Context.defineAssetPath(function (pathname, options) {
  var asset = this.environment.findAsset(pathname, options);
  return '/assets/' + asset.digestPath;
});

Context.registerHelper

    • Context.registerHelper
    • 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 Environment#ContextClass (see Environment#registerHelper as well).

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

// equals to

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

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') %>')

Context#assetPath

    • Context#assetPath(pathname, options)
      • String

Helper that returns path to asset and that acts like a 'base' method for other *Path helpers.

Exposed to the engines as asset_path helper.

By default this method is not implemented, and you must provide it's implementation that will fit your needs, e.g.:

environment.ContextClass.defineAssetPath(function (pathname, options) {
  var asset = this.environment.findAsset(pathname, options);
  return '/assets/' + asset.digestPath;
});

Once implemented, you can use asset_path helper, e.g.:

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

Context#audioPath

    • Context#audioPath(pathname)
      • String

Wrapper over Context#assetPath for audio assets. Exposed to the engines as audio_path helper.

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.

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 Context#dependOn, this will include recursively the target asset's dependencies.

Context#evaluate

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

Reads pathname and runs processors on the file.

Context#fontPath

    • Context#fontPath(pathname)
      • String

Wrapper over Context#assetPath for font assets. Exposed to the engines as font_path helper.

Context#imagePath

    • Context#imagePath(pathname)
      • String

Wrapper over Context#assetPath for image assets. Exposed to the engines as image_path helper.

Context#isAssetRequirable

    • Context#isAssetRequirable(pathname)
      • Boolean

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

Context#javascriptPath

    • Context#javascriptPath(pathname)
      • String

Wrapper over Context#assetPath for javascript assets. Exposed to the engines as javascript_path helper.

Context#requireAsset

    • Context#requireAsset(pathname)
      • Void

requireAsset 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") %>

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 Base#resolve when needed.

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.

Context#stylesheetPath

    • Context#stylesheetPath(pathname)
      • String

Wrapper over Context#assetPath for stylesheet assets. Exposed to the engines as stylesheet_path helper.

Context#videoPath

    • Context#videoPath(pathname)
      • String

Wrapper over Context#assetPath for video assets. Exposed to the engines as video_path helper.

Context#contentType

    • Context#contentType
      • String

Returns content type of file

'application/javascript'
'text/css'

Context#context

Returns the context itself.

Context#logicalPath

    • Context#logicalPath
      • String

Returns logical path without any file extensions.

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

Context#relativePath

    • Context#relativePath
      • String

Returns AssetAttributes#relativePath of current file.

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.

Context#subclass

internal
    • Context#subclass
      • Function

Returns new subclass of Context.

CssoCompressor

Description

Engine for CSS minification. You will need csso Node module installed:

npm install csso
SUBCLASS OF

Template

CsswringCompressor

Description

Engine for CSS minification. Less powerful than CSSO, but with sourcemaps support. You will need csswring Node module installed:

npm install csswring
SUBCLASS OF

Template

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

DirectiveProcessor#processDirectives

    • DirectiveProcessor#processDirectives()
      • Void

Executes handlers for found directives.

See Also:

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"]]]

DirectiveProcessor#processedHeader

    • DirectiveProcessor#processedHeader
      • String

Returns the header String with any directives stripped.

DirectiveProcessor#processedSource

    • DirectiveProcessor#processedSource
      • String

Returns the source String with any directives stripped.

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

This is a mixed-type engine that can be used as a 'backend' of JstEngine as well as standalone 'middleware' processor in a pipeline.

SUBCLASS OF

Template

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

Engines#getEngines

    • Engines#getEngines(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

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);

Engines#engineExtensions

    • Engines#engineExtensions
      • Array

Returns an Array of engine extension Strings.

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

Environment

Description

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

SUBCLASS OF

Base

Constructor

Instance properties

Environment.new

    • new Environment(root)

Environment#expireIndex

internal
    • Environment#expireIndex()
      • Void

Reset assets internal cache.

Environment#findAsset

    • Environment#findAsset(path[, options])

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

Environment#registerHelper

    • Environment#registerHelper
    • Environment#registerHelper(helpers)
      • Void

Proxy to Context.registerHelper of current Environment#ContextClass.

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

// shorthand syntax of

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

Environment#ContextClass

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

See Also

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.

Environment#sourceRoot

    • Environment#sourceRoot
      • String

sourceRoot property for generated source maps. Can be used to beatify nesting level in dev tools.

Default: '/'.

FileStore

Description

Cache backend that keeps assets cache on FS.

Usage
env.cache = new FileStore('/path/to/cache');

Constructor

FileStore.new

    • new FileStore(root)
    • root
      • String
    • cache path root

HandlebarsEngine

Description

Engine for the Handlebars template language. You will need handlebars Node module installed in order to use Mincer with *.hbs files:

npm install handlebars

This is a mixed-type engine that can be used as a 'backend' of JstEngine as well as standalone 'middleware' processor in a pipeline.

NOTICE Generated functions require you to have handlebars client runtime to be required:

//= require handlebars.runtime
//= require templates/hello
SUBCLASS OF

Template

Hash

internal

Description

Thin wraper over Object used internally to keep lists of processors.

Constructor

Instance methods

Hash.new

    • new Hash(defaulter)
    • defaulter
      • Function
    • default value generator

Hash#clone

Makes a copy of a Hash.

processors.get('text/css').length; // => 1

processors_copy = processors.clone(); processors_copy.get('text/css').push(MyMegaProcessor);

processors.get('text/css').length; // => 1 processors_copy.get('text/css').length; // => 2

Used upon Environment init - clone globally registered processors

Hash#get

    • Hash#get(key)
      • Mixed
    • key
      • String

Returns value associated with given key:

processors.get('text/css').push(DirectiveProcessor);

Associates key with value generated by defaulter if it does not exists yet.

Hash#set

    • Hash#set(key, val)
      • Void
    • key
      • String
    • val
      • Mixed

Set value for a key:

old_val = processors.get('text/css'); new_val = _.without(old_val, MyMegaProcessor); processors.set('text/css', new_val);

Used to reset value of a key.

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 Environment#index.

SUBCLASS OF

Base

Class methods

Instance methods

Instance properties

Index.getFileDigest

    • Index.getFileDigest(pathname)
      • crypto.Hash

Cached version of Base#getFileDigest.

Index#expireIndex

internal
    • Index#expireIndex()
      • Void

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

Index#findAsset

    • Index#findAsset(pathname[, options])

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

Index#index

Self-reference to provide same interface as in Environment.

JadeEngine

Description

Engine for the Jade template language. You will need jade Node modules installed in order to use Mincer with *.jade files:

npm install jade

This is a mixed-type engine that can be used as a 'backend' of JstEngine as well as standalone 'middleware' processor in a pipeline.

NOTICE Generated functions require you to have jade client runtime to be required:

//= require jade-runtime
//= require templates/hello
SUBCLASS OF

Template

Class methods

JadeEngine.configure

    • JadeEngine.configure(opts)
      • Void
    • opts
      • Object

Allows to set Jade compilation opts. See Jade compilation opts for details.

Default: {}.

Example
JadeEngine.configure({self: true});

JstEngine

Description

Engine for the JST files. This is a core wrapper, that wraps function prepared by view renderers like Haml Coffee.

SUBCLASS OF

Template

Class methods

JstEngine.configure

    • JstEngine.configure(ns)
      • Void
    • ns
      • String

Allows to set JST global scope variable name.

Default: 'this.JST'.

Example
JstEngine.configure('this.tpl');

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

Logger

Description

Provides unified logging interface for Mincer.

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

Logger.debug

    • Logger.debug(message)
      • Void

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

Logger.error

    • Logger.error(message)
      • Void

Used for logging errors.

Logger.info

    • Logger.info(message)
      • Void

Used for important messages.

Logger.level

    • int
      • Integer
    • A number respresenting which levels to log

Allows to mute lower log levels. Any log level less than the number specified will be ignored.

Log levels
  • logger.LOG_LEVEL : 0
  • logger.DEBUG_LEVEL : 1
  • logger.INFO_LEVEL : 2
  • logger.WARN_LEVEL : 3
  • logger.ERROR_LEVEL : 4
Examples
Logger.level(Logger.WARN_LEVEL);

Logger.Level(4);

Logger.log

    • Logger.log(level, message)
      • Void

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

Logger.use

    • 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:

Example
Logger.use(console);

Logger.warn

    • Logger.warn(message)
      • Void

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

MacroProcessor

Description

MacroProcessor is simple and effective replacement for EJS, when user needs just embed constants into file. Macros content is replaced with evaluated value. You can use all mincer helpers (locals) in expression.

Example of use:
var url = "'$$ asset_path('/vendor/jquery') $$'";
var str = '"$$ function () { var foo = my_super_helpers(5) + 23; return foo; } $$"';
var str = '$$ JSON.stringify(asset_path("/vendor/jquery")) $$';

MacroProcessor processor is always on, but not assigned to any file extention. You can enable macros with configure() method.

Example of configure:
var mincer = require('mincer');

// Enable for `.js` / `.css` / `.jade`
mincer.Macro.configure(['.js', '.css', '.jade']);

// Enable for `.js` only
mincer.Macro.configure('.js', true);
SUBCLASS OF

Template

Class methods

MacroProcessor.configure

    • MacroProcessor.configure(extention, enable)
      • Void
    • extention
      • String
      • Array
    • extention or array of extentions to process

    • enable
      • Boolean
    • false - disable, true or undefined - enable

on / off macroses for specified extentions.

Example
// Enable for `.js` / `.css` / `.jade`
MacroProcessor.configure(['.js', '.css', '.jade']);
MacroProcessor.configure(['.js', '.css', '.jade'], true);

// Enable for `.js` only
MacroProcessor.configure('.js', true);

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

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");

Manifest#compile

    • Manifest#compile(files[, options])
      • Object
    • files
      • Array
    • options
      • Object
options:
  • sourceMaps (false) - set true to write sourcemap files
  • embedMappingComments (false) - set true to embed sourcemap url into created files
  • compress (false) - set true to also create gzipped files
  • noSourceMapProtection (false) - set true to skip adding XSSI protection header

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.

Returns manifest content on success. Throws exception on error.

var data = manifest.compile(["app.js"]);

//  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"
//      },
//      ...
//    }
//  }

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"
}

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" } }

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

Mime#getExtensionForMimeType

    • Mime#getExtensionForMimeType(type)
      • String

Returns extension for mime type.

Mime#getMimeType

    • Mime#getMimeType(ext)
      • String

Returns the mime type for the extension.

Mime#registerMimeType

    • Mime#registerMimeType(type, ext)
      • Void

Register new mime type.

Mime#registeredMimeTypes

    • Mime#registeredMimeTypes
      • Mimoza

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

Mincer

Description

This is a main entry point of the module (an object that you get by calling require('mincer'). You can get access 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

Mincer.createServer

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

Mincer.Autoprefixer

Mincer.CharsetNormalizer

Mincer.CoffeeEngine

Mincer.CssoCompressor

Mincer.CsswringCompressor

Mincer.DirectiveProcessor

Mincer.EjsEngine

Mincer.Environment

Mincer.FileStore

Mincer.HandlebarsEngine

Mincer.JadeEngine

Mincer.JstEngine

Mincer.LessEngine

Mincer.logger

read-only

Mincer.MacroProcessor

Mincer.Manifest

Mincer.PugEngine

Mincer.SafetyColons

Mincer.SassEngine

Mincer.Server

Mincer.StylusEngine

Mincer.Template

Mincer.UglifyCompressor

Mincer.VERSION

read-only
    • Mincer.VERSION
      • String

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

Paths#appendPath

    • Paths#appendPath(path)
      • Void

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

Paths#clearPaths

    • Paths#clearPaths()
      • Array

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.

Returns list of previously registered paths.

Paths#prependPath

    • Paths#prependPath(path)
      • Void

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

Paths#extensions

    • Paths#extensions
      • Array

Returns an Array of extensions.

These extensions maybe omitted from logical path searches.

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

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 Paths#appendPath, Paths#prependPath, and Paths#clearPaths.

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.

ProcessedAsset

internal

Description

ProcessedAssets are internal representation of processable files.

SUBCLASS OF

Asset

Instance methods

ProcessedAsset.new

    • new ProcessedAsset()

See new Asset for details.

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.

Processing

internal

Description

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

Instance properties

Processing#addEngineToTrail

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

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

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.

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.

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.

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(...));
});

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(...));
});

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(...));
});

Processing#unregisterBundleProcessor

    • Processing#unregisterBundleProcessor(mimeType, klass)
      • Void

Remove BundleProcessor klass for mime_type.

unregisterBundleProcessor('text/css', CharsetNormalizer);

Processing#unregisterPostProcessor

    • Processing#unregisterPostProcessor(mimeType, klass)
      • Void

Remove Postprocessor klass for mime_type.

unregisterPostprocessor('text/css', DirectiveProcessor);

Processing#unregisterPreProcessor

    • Processing#unregisterPreProcessor(mimeType, klass)
      • Void

Remove Preprocessor klass for mime_type.

unregisterPreprocessor('text/css', DirectiveProcessor);

Processing#formatExtension

    • Processing#formatExtension
      • Array

Returns an Array of format extension Strings.

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

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

Processor.create

    • Processor.create(name, func)
      • Function

Returns new Processor subclass.

PugEngine

Description

Engine for the Pug template language. You will need pug Node modules installed in order to use Mincer with *.pug files:

npm install pug

This is a mixed-type engine that can be used as a 'backend' of JstEngine as well as standalone 'middleware' processor in a pipeline.

NOTICE Generated functions require you to have pug client runtime to be required:

//= require pug-runtime
//= require templates/hello
SUBCLASS OF

Template

Class methods

PugEngine.configure

    • PugEngine.configure(opts)
      • Void
    • opts
      • Object

Allows to set Pug compilation opts. See Pug compilation opts for details.

Default: {}.

Example
PugEngine.configure({self: true});

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

SassEngine

Description

Engine for the SASS/SCSS compiler. You will need node-sass Node module installed in order to use Mincer with *.sass or *.scss files:

npm install node-sass
SUBCLASS OF

Template

Class methods

SassEngine.configure

    • SassEngine.configure(opts)
      • Void
    • opts
      • Object

Allows to set Sass compilation opts.

Default: {}.

Example
SassEngine.configure({ sourceComments: true });

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'];
var srv = new Server(env.index, manifest.compile(files));

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

Server.new

    • new Server(environment[, manifest])

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

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

Server#compile

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

Finds and compiles given asset.

Server#handle

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

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

Exampple

var assetsSet

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 Mincer.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 object 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.

StaticAsset

internal

Description

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

SUBCLASS OF

Asset

Constructor

StaticAsset.new

    • new StaticAsset()

See new Asset for details.

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 methods

StylusEngine.configure

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

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

var nib = require('nib');

Stylus.configure(function (style) {
  style.use(nib());
});

Default: function (_) { 'do nothing'; }

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 = function (context, locals) {
  var data = this.data.toLowerCase();
  return data;
};

Constructor

Class properties

Instance methods

Instance properties

Template.new

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

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

Template.libs

    • Template.libs
      • Object

Third-party libs.

Example
Mincer.Template.libs["ejs"] = require("ejs");

Template#evaluate

    • Template#evaluate(context, locals)
      • data
    • context
      • Context
    • locals
      • Object

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) {
  var data = this.data.replace(this.secret, '***TOP-SECRET***');
  return data;
};

Template#data

internal
    • Template#data
      • String

A source string to be compiled.

See Also

UglifyCompressor

Description

Engine for CSS minification. You will need uglify-js Node module installed:

npm install uglify-js
SUBCLASS OF

Template

Class methods

UglifyCompressor.configure

    • UglifyCompressor.configure(opts)
      • Void
    • opts
      • Object

Allows to set UglifyJS options. See UglifyJS minify options for details.

Default: {}.

Example
UglifyCompressor.configure({mangle: false});