MaXFalstein / express-minify

Automatically minify and cache your javascript and css files.

Home Page:https://npmjs.org/package/express-minify

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

express-minify

Build Status npm version npm download counter

Dependency Status devDependency Status

NodeICO

Automatically minify and cache your javascript and css files.

It also supports LESS/SASS/Stylus/CoffeeScript compiling and minifying.

Installation

npm install express-minify

Basic Usage

express-minify takes care of all responses. You don't even need to pass a source directory as other minifying middlewares.

var minify = require('express-minify');
app.use(minify());

It's very easy and elegant to integrate express-minify with express.static and compression.

app.use(compression());
app.use(minify());
app.use(express.static(__dirname + '/static'));

Note that the order of the middlewares is important. In the example above, we want to: serve static files → for JS & CSS: minify → GZip → send to user, so we have such orders.

Default Options

app.use(minify({
  cache: false,
  uglifyJS: undefined,
  cssmin: undefined,
  onerror: undefined,
  js_match: /javascript/,
  css_match: /css/,
  sass_match: /scss/,
  less_match: /less/,
  stylus_match: /stylus/,
  coffee_match: /coffeescript/,
  json_match: /json/,
}));
  • cache: String | false

    The directory for cache storage (must be writeable). Pass false to cache in the memory (not recommended). If you want to disable the cache, see Disable minifying or caching for a response.

  • uglifyJS: Object

    Customize UglifyJS instance (require('uglify-js')).

  • cssmin: Object

    Customize cssmin instance (require('cssmin')).

  • onerror: Function

    Handle compiling errors or minifying errors. You can determine what to respond when facing such errors. See Customize onError behavior.

  • js_match: RegExp

    Matches JavaScript content-type.

  • css_match: RegExp

    Matches CSS content-type.

  • sass_match: RegExp

    Matches SASS content-type.

  • less_match: RegExp

    matches LESS content-type.

  • stylus_match: RegExp

    Matches Stylus content-type.

  • coffee_match: RegExp

    Matches CoffeeScript content-type.

  • json_match: RegExp

    Matches JSON content-type.

Per-response Options

Those options only applied to the specified response.

  • res._skip

    Pass true to disable all kind of processing: no compiling, no minifying.

  • res._no_minify

    Pass true to disable minifying, suitable for already-minified contents. example

  • res._no_cache

    Pass true to disable caching the response data, suitable for dynamic contents. example

UglifyJs Options

  • res._uglifyMangle

    Pass false to disable mangling names. example

  • res._uglifyOutput

    Pass an object if you wish to specify additional UglifyJS output options. example

  • res._uglifyCompress

    Pass an object to specify custom UglifyJS compressor options (pass false to skip).

Examples

File Cache

In default, express-minify use memory cache. You can change to using file cache:

app.use(minify({cache: __dirname + '/cache'}));

Compile and Minify CoffeeScript/LESS/SASS/Stylus

express-minify can automatically compile your files and minify it without the need of specifying a source file directory. Currently it supports coffee-script, less, sass and stylus.

To enable this feature, first of all you need to install those modules by yourself:

# you needn't install all of those modules
# only choose what you want
npm install coffee-script less node-sass stylus --save

Then you need to define MIME for those files:

// visit http://localhost/test.coffee

express.static.mime.define(
{
    'text/coffeescript':  ['coffee'],
    'text/less':          ['less'],
    'text/x-scss':        ['scss'],
    'text/stylus':        ['styl']
});

app.use(minify());

Done!

Notice: Those modules are listed in devDependencies for testing purpose. If you don't manually add them to your project's dependencies, you may face errors when switching from npm dev install to npm production install because they are no longer installed by express-minify.

Customize onError Behavior

Errors thrown by CoffeeScript/LESS/SASS/Stylus module are compiling errors and errors thrown by UglifyJS/cssmin/JSON module are minifying errors.

The default behavior is to return the error message for compiling errors and return the original content for minifying errors.

You can change this behavior or get notified about the error by providing onerror in options:

var minify = require('express-minify');

/*

err: the Error object
stage: "compile" or "minify"
assetType: The type of the source code, can be one of
  minify.Minifier.TYPE_TEXT
  minify.Minifier.TYPE_JS
  minify.Minifier.TYPE_CSS
  minify.Minifier.TYPE_SASS
  minify.Minifier.TYPE_LESS
  minify.Minifier.TYPE_STYLUS
  minify.Minifier.TYPE_COFFEE
  minify.Minifier.TYPE_JSON
minifyOptions: Minification options
body: Source code (string)
callback: (err, body) return the final result as string in this callback function.
  If `err` is null, the final result will be cached.

*/

var myErrorHandler = function (err, stage, assetType, minifyOptions, body, callback) {
  console.log(err);
  // below is the default implementation
  if (stage === 'compile') {
    callback(err, JSON.stringify(err));
    return;
  }
  callback(err, body);
};

app.use(minify({
  onerror: myErrorHandler
}));

You can also access the default implementation from minify.Minifier.defaultErrorHandler.

Customize UglifyJS/cssmin Instance

If you want to use your own UglifyJS/cssmin instance (for example, use a different branch to support ES6), you can pass them to the options.

var myUglifyJS = require('uglify-js');
var myCssmin = require('cssmin');
app.use(minify({
  uglifyJS: myUglifyJS,
  cssmin: myCssmin,
}));

Notice: You may need to clear file cache after switching to your own UglifyJS/cssmin instance because cache may be outdated.

Specify UglifyJs Options

response._uglifyMangle: pass false to skip mangling names.

Example: Disable mangle for AngularJs.

app.use(function(req, res, next)
{
    // do not mangle -angular.js files
    if (/-angular\.js$/.test(req.url)) {
        res._uglifyMangle = true;
    }
    next();
});
app.use(minify());

response._uglifyOutput: specify UglifyJs additional output options.

Example: Preserve comments for specific files.

app.use(function(req, res, next)
{
    if (/\.(user|meta)\.js$/.test(req.url)) {
        res._uglifyOutput = {
            comments: true
        };
    }
    next();
});

response._uglifyCompress: specify UglifyJs custom compressor options.

Process Dynamic Response

express-minify is able to handle all kind of responses, such as non-static responses.

var responseJS = 
    "(function(window, undefined)\n" +
    "{\n" +
    "\n" +
    "    var hello = 'hello';\n" +
    "\n" +
    "    var world = 'world';\n" +
    "\n" +
    "    alert(hello + world);\n" +
    "\n" +
    "})(window);"

app.use(minify());
app.get('/response.js', function(req, res)
{
    res.setHeader('Content-Type', 'application/javascript');
    res.end(responseJS);
});

Disable Minifying or Caching for a Response

If you don't want to minify a specific response, just use response._no_minify = true.

If you want to minify a response but don't want to cache it (for example, dynamic response data), use: response._no_cache = true.

Example:

app.use(function(req, res, next)
{
    // for all *.min.css or *.min.js, do not minify it
    if (/\.min\.(css|js)$/.test(req.url)) {
        res._no_minify = true;
    }
    next();
});
app.use(minify());

Yet another example:

app.use(minify());
app.get('/server_time_min.jsonp', function(req, res)
{
    var obj = {
        'ok': true,
        'data': {
            'timestamp': new Date().getTime()
        }
    };

    // minify this response, but do not cache it
    res._no_cache = true;
    res.setHeader('Content-Type', 'application/javascript');
    res.send("callback(" + JSON.stringify(obj, null, 4) + ");");
});
app.get('/server_time.jsonp', function(req, res)
{
    var obj = {
        'ok': true,
        'data': {
            'timestamp': new Date().getTime()
        }
    };

    // do not minify this response
    res._no_minify = true;
    res.setHeader('Content-Type', 'application/javascript');
    res.send("callback(" + JSON.stringify(obj, null, 4) + ");");
});

WARNING: Do NOT set _no_minify between res.write and res.end.

Note

If you are using cluster, it is strongly recommended to enable file cache. They can share file caches.

Change Log

0.2.0

  • Support onerror
  • Minimum required NodeJs version changed to 0.12.0 for fs.access.

0.1.7

  • Support customizing UglifyJS/cssmin instance

0.1.6

  • Make node-sass, stylus, less, coffee-script dependency optional, now developers need to manually install those modules to enable compiling

0.1.5

  • Fix MIME for Js
  • Fix JSON minify performance issue

0.1.4

  • Add some useful badges #27
  • Update dependencies
  • Support JSON minify #25
  • Start to use travis-ci online build testing

0.1.3

0.1.2

  • Added res._skip.
  • Modified behaviour of res._no_minify. Now it will only disable minifying and won't cause precompiling not working. #17
  • Fixed cache bugs with response options.

0.1.1

  • Added fallback for res._no_mangle = true (Please use res._uglifyMangle = false)
  • Update dependencies

0.1.0

  • Changed disabling mangle: res._no_mangle = true => res._uglifyMangle = false
  • Added support for passing additional UglifyJs options: res._uglifyCompress, res._uglifyOutput #15

0.0.11

  • Update dependencies #11

0.0.10

  • Added tests

  • Fixed SASS compiling

  • Fixed express-compression compatibility

0.0.9

  • Added support for res._no_mangle #10

0.0.8

  • Removed options of whitelist and blacklist

  • Added support for res._no_cache #5

  • Node v0.10 compatible

0.0.7

  • Changed options's default blacklist to [/\.min\.(css|js)$/]

  • Replaced uglifycss with cssmin

  • Dropped support for .sass (sass/node-sass#12)

  • Fixed #3

0.0.6

  • Support for blacklist and whitelist #2

0.0.5

  • Added support for res._no_minify

  • Fixed #1

0.0.4

  • Support for LESS/SASS/Stylus/CoffeeScript parsing and minifying

0.0.3

  • Support for file cache

  • Fixed the bug of non-string path

0.0.2

  • Support for dynamic minifying

License

The MIT License (MIT)

Copyright (c) 2016 Breezewish

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

Automatically minify and cache your javascript and css files.

https://npmjs.org/package/express-minify

License:MIT License


Languages

Language:JavaScript 100.0%