Transparent file compilation and dependency management for Node’s connect framework in the spirit of the Rails asset pipeline.
connect-assets can:
- Serve
.js.coffee
(CoffeeScript) files as compiled.js
- Concatenate
.js.coffee
and.js
together. - Serve
.css.styl
(Stylus) as compiled.css
- Serve
.css.less
(Less) as compiled.css
- Serve
.css.sass
or.css.scss
(SASS) as compiled.css
- Serve
.jst.jade
(Jade templates) as compiled JavaScript functions (be sure to include the Jade runtime — see below). - Serve
.jst.ejs
as compiled JavaScript functions. - Preprocess
style.css.ejs
andscript.js.ejs
with EJS — just append.ejs
to any file. - Serve files with a cache-control token and use a far-future expires header for maximum efficiency.
- Avoid redundant git diffs by storing compiled
.js
and.css
files in memory rather than writing them to the disk when in development.
First, install it in your project's directory:
npm install connect-assets
Also install any specific compilers you'll need, e.g.:
npm install coffee-script
npm install stylus
npm install less
npm install node-sass
npm install jade
npm install ejs
Then add this line to your app's configuration:
app.use(require("connect-assets")());
Finally, create an assets
directory in your project and throw all assets compiled into JavaScript into /assets/js
and all assets compiled into CSS into /assets/css
.
connect-assets provides three global functions named js
, css
, and assetPath
. Use them in your views. They return the HTML markup needed to include the most recent version of your assets (or, the path to the asset), taking advantage of caching when available. For instance, in a Jade template, the code
!= css("normalize")
!= js("jquery")
(where `!= is Jade's syntax for running JS and displaying its output) results in the markup
<link rel="stylesheet" href="/css/normalize-[hash].css" />
<script src="/js/jquery-[hash].js"></script>
You can pass a Hash of special attributes to helper method css
or js
:
!= css("normalize", { 'data-turbolinks-track': true } })
!= js("jquery", { async: true })
Results in:
<link rel="stylesheet" href="/css/normalize-[hash].css" data-turbolinks-track />
<script src="/js/jquery-[hash].js" async></script>
You can also reference image paths via the assetPath
helper. First, you must specify the
path to your images via the paths
option e.g:
...
var assets = require('connect-assets');
app.use(assets({
paths: [
'assets/css',
'assets/js',
'assets/img'
]
}));
You can then use the assetPath
helper in your Jade like so:
img(src="#{assetPath('image-name.png')}")
Would result in:
<img src="/assets/img/image-name-[hash].png">
You can indicate dependencies in your .js.coffee
and .js
files using the Sprockets-style syntax.
In CoffeeScript:
#= require dependency
In JavaScript:
//= require dependency
When you do so, and point the js
function at that file, two things can happen:
- By default, you'll get multiple
<script>
tags out, in an order that gives you all of your dependencies. - If you passed the
build: true
option to connect-assets (enabled by default whenenv == 'production'
), you'll just get a single tag, wich will point to a JavaScript file that encompasses the target's entire dependency graph—compiled, concatenated, and minified (with UglifyJS).
If you want to bring in a whole folder of scripts, use //= require_tree dir
instead of //= require file
.
You can also indicate dependencies in your .css
files using the Sprockets-style syntax.
/*= require reset.css */
body { margin: 0; }
See Mincer for more information.
If you like, you can pass any of these options to the first parameter of the function returned by require("connect-assets")
:
Option | Default Value | Description |
---|---|---|
paths | ["assets/js", "assets/css"] | The directories that assets will be read from, in order of preference. |
helperContext | global | The object that helper functions (css, js, assetPath) will be attached to. |
servePath | "assets" | The virtual path in which assets will be served over HTTP. If hosting assets locally, supply a local path (say, "assets"). If hosting assets remotely on a CDN, supply a URL: "http://myassets.example.com/assets". |
precompile | ["*.*"] | An array of assets to precompile while the server is initializing. Patterns should match the filename only, not including the directory. |
build | dev: false; prod: true | Should assets be saved to disk (true), or just served from memory (false)? |
buildDir | dev: false; prod: "builtAssets" | The directory to save (and load) compiled assets to/from. |
compile | true | Should assets be compiled if they don’t already exist in the buildDir ? |
compress | dev: false; prod: true | Should assets be minified? If enabled, requires uglify-js and csswring . |
gzip | false | Should assets have gzipped copies in buildDir ? |
fingerprinting | dev: false; prod: true | Should fingerprints be appended to asset filenames? |
sourceMaps | dev: true; prod: false | Should source maps be served? |
This package depends on mincer, which is quite configurable by design. Many options from mincer are not exposed through connect-assets in the name of simplicity.
As asset compliation happens immediately after connect-assets is initialized, any changes that affect the way mincer compiles assets should be made during initialization. A custom initialization function can be passed to connect-assets as a second argument to the function returned by require("connect-assets")
:
app.use(require("connect-assets")(options, function (instance) {
// Custom configuration of the mincer environment can be placed here
instance.environment.registerHelper(/* ... */);
}));
connect-assets includes a command-line utility, connect-assets
, which can be used to precompile assets on your filesystem (which you can then upload to your CDN of choice). From your application directory, you can execute it with ./node_modules/.bin/connect-assets [options]
.
Usage: connect-assets [-h] [-v] [-gz] [-ap] [-i [DIRECTORY [DIRECTORY ...]]]
[-c [FILE [FILE ...]]] [-o DIRECTORY]
Precompiles assets supplied into their production-ready form, ready for
upload to a CDN or static file server. The generated manifest.json is all
that is required on your application server if connect-assets is properly
configured.
Optional arguments:
-h, --help Show this help message and exit.
-v, --version Show program's version number and exit.
-i [DIRECTORY [DIRECTORY ...]], --include [DIRECTORY [DIRECTORY ...]]
Adds the directory to a list of directories that
assets will be read from, in order of preference.
Defaults to 'assets/js' and 'assets/css'.
-c [FILE [FILE ...]], --compile [FILE [FILE ...]]
Adds the file (or pattern) to a list of files to
compile. Defaults to all files.
-o DIRECTORY, --output DIRECTORY
Specifies the output directory to write compiled
assets to. Defaults to 'builtAssets'.
-s PATH, --servePath PATH
The virtual path in which assets will be served
over HTTP. If hosting assets locally, supply a
local path (say, "assets"). If hosting assets
remotely on a CDN, supply a URL.
-gz, --gzip
Enables gzip file generation, which is disabled by
default.
-ap, --autoprefixer Enables autoprefixer during compilation.
Follows in the footsteps of sstephenson's Sprockets, through the Mincer project.
Take a look at the contributors who make this project possible.