Fork me on GitHub

Mincer - assets processor

Build Status

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.

Also, mincer cares about sourcemaps support (sprockets doesn't yet).

See Sprockets and Mincer API Documentation for more details.

Supported engines are described in Wiki. If you wish to add new engine support - read tutorial.

Notice on upgrade 0.5.x -> 1.0.x

Sourcemaps support added. See docs and examples for details.

  • environment.enable('source_maps')
  • use csswring css compressor instead of csso, for sourcemaps support
  • removed /?body=1 stuff as replaced with sourcemaps
  • removed Asset.writeTo() method.
  • Manifest.compile() is now sync and throw exception on error.
  • Removed non mainstream engines: eco, coco, haml-coffee, livescript.

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

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.

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 Haml Coffee

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.hamlc
%div= Hello, %span= #{ @name }!
// application.js
//= require templates/hello
$("#hello").html(JST["templates/hello"]({ name: "Sam" }));

Mincer supports two template languages: Haml Coffee and Jade.

If coffee-script and haml-coffee are available to your application, you can use Haml Cofee templates in Mincer. Haml Coffee templates have the extension .jst.hamlc.

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

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 () {
  return 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

Instance 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#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 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#relativePath

    • Asset#relativePath
      • String

Returns AssetAttributes#relativePath of current file.

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

    • AssetAttributes#relativePath
      • String

Returns full path name relative to environment's root.

instance property

AssetAttributes#searchPaths

    • AssetAttributes#searchPaths
      • Array

Returns paths search the load path for.

class

Autoprefixer

Description

Post processor that runs autoprefixer for css. You will need autoprefixer Node module installed:

npm install autoprefixer
SUBCLASS OF

Template

Class methods

class method

Autoprefixer.configure

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

Allows to set Autoprefixer requirements.

Default: undefined.

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

Base

internal

Description

Base class for Environment and Index.

INCLUDES

Constructor

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

    • Base#cache
      • Mixed

Cache backend.

Default: null.

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. .jsand.css` files.

SUBCLASS OF

Asset

Constructor

Instance methods

Instance properties

constructor

BundledAsset.new

    • new BundledAsset()

See new Asset 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.

mixin

Caching

internal

Description

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

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 and *.litcoffee files:

npm install coffee-script
SUBCLASS OF

Template

Class methods

class method

CoffeeEngine.configure

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

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

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

Compressing

internal

Description

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

Instance properties

instance method

Compressing#getCompressors

    • Compressing#getCompressors()
      • Object

Returns compressors groupped by mime-type.

instance method

Compressing#registerCompressor

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

Registers a compressor klass as name for mimeType.

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

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.

instance property

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.

mixin

Configuring

internal

Description

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

instance method

Configuring#disable

    • Configuring#disable(name)
      • Void

Disable configuration.

Example
env.disable('autoprefixer');
instance method

Configuring#enable

    • Configuring#enable(name)
      • Void

Enable configuration.

Example
env.enable('autoprefixer');
instance method

Configuring#getConfigurations

    • Configuring#getConfigurations()
      • Object

Returns copy of registered configurations.

instance method

Configuring#isEnabled

    • Configuring#isEnabled(name)
      • Void

Tells whenever given configuration enabled or not.

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

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

constructor

Context.new

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

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;
});
class method

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
});
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#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') %>) }
instance method

Context#audioPath

    • Context#audioPath(pathname)
      • String

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

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

instance method

Context#evaluate

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

Reads pathname and runs processors on the file.

instance method

Context#fontPath

    • Context#fontPath(pathname)
      • String

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

instance method

Context#imagePath

    • Context#imagePath(pathname)
      • String

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

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

    • Context#javascriptPath(pathname)
      • String

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

instance method

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") %>
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 Base#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 method

Context#stylesheetPath

    • Context#stylesheetPath(pathname)
      • String

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

instance method

Context#videoPath

    • Context#videoPath(pathname)
      • String

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

instance property

Context#contentType

    • Context#contentType
      • String

Returns content type of file

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

Context#context

Returns the context itself.

instance property

Context#logicalPath

    • Context#logicalPath
      • String

Returns logical path without any file extensions.

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

Context#relativePath

    • Context#relativePath
      • String

Returns AssetAttributes#relativePath of current file.

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

CssoCompressor

Description

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

npm install csso
SUBCLASS OF

Template

class

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

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()
      • 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

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

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 Index#findAsset of the one time Environment#index instance. Index#findAsset automatically pushes cache here.

instance method

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

instance property

Environment#sourceRoot

    • Environment#sourceRoot
      • String

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

Default: '/'.

class

FileStore

Description

Cache backend that keeps assets cache on FS.

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

Constructor

constructor

FileStore.new

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

class

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

class

Hash

internal

Description

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

Constructor

Instance methods

constructor

Hash.new

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

instance method

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

instance method

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.

instance method

Hash#set

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

Set value for a key:

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

Used to reset value of a key.

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

SUBCLASS OF

Base

Class methods

Instance methods

Instance properties

class method

Index.getFileDigest

    • Index.getFileDigest(pathname)
      • crypto.Hash

Cached version of Base#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 Base#findAsset. Pushes cache to the upstream environment as well.

instance property

Index#index

Self-reference to provide same interface as in Environment.

class

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

class method

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

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

class method

JstEngine.configure

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

Allows to set JST global scope variable name.

Default: 'this.JST'.

Example
JstEngine.configure('this.tpl');
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 Logger.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:

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])
      • 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

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

class property

Mincer.CharsetNormalizer

class property

Mincer.CoffeeEngine

class property

Mincer.CssoCompressor

class property

Mincer.CsswringCompressor

class property

Mincer.DirectiveProcessor

class property

Mincer.EjsEngine

class property

Mincer.Environment

class property

Mincer.FileStore

class property

Mincer.HandlebarsEngine

class property

Mincer.JadeEngine

class property

Mincer.JstEngine

class property

Mincer.LessEngine

class property

Mincer.logger

read-only
class property

Mincer.Manifest

class property

Mincer.SafetyColons

class property

Mincer.SassEngine

class property

Mincer.Server

class property

Mincer.StylusEngine

class property

Mincer.Template

class property

Mincer.UglifyCompressor

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 Paths#appendPath, Paths#prependPath, and Paths#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 Asset 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 properties

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

    • Processing#formatExtension
      • Array

Returns an Array of format extension Strings.

// => ['.js', '.css']
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

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

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

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 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 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 Asset 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 methods

class method

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'; }

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

Constructor

Class properties

Instance methods

Instance properties

constructor

Template.new

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

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

class property

Template.libs

    • Template.libs
      • Object

Third-party libs.

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

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;
};
instance property

Template#data

internal
    • Template#data
      • String

A source string to be compiled.

See Also
class

UglifyCompressor

Description

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

npm install uglify-js
SUBCLASS OF

Template

Class methods

class method

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