Question

I am used to using Rails, and I really enjoy the asset pipeline. The ease that CSS & JS just is minified and bundled automatically when you upload your app.

What is the best way to have something similar in NodeJS, or should the deployment process be a bit different from what I am used to in Rails?

Was it helpful?

Solution

You can use grunt.js as a task runner that you run to take care of all the minification/preprocessing you want to do.

For minifying js you can use https://github.com/gruntjs/grunt-contrib-uglify

For minifying css you can use https://github.com/gruntjs/grunt-contrib-cssmin

OTHER TIPS

Simple regex CSS minifier/compressor

PS: I hate to use different frameworks and libraries where they are not needed. So, I want propose my easiest way that allows to minify and simplify CSS.

Features

  • Remove all comments
  • Remove all empty declarations
  • Remove all whitespaces that are unnecessary
    (including around the meta characters, such as { } ( ) : ; > ~ + etc.)
  • Remove the last ";" in a rule declaration
  • Remove leading zero in float value. For example: 0.5 > .5
  • Convert HEX color to short value when it's possible. For example: #CCCCCC > #CCC
  • Remove for all zero values units (such as %,px,pt,pc,rem,em,ex,cm,mm,in) that are unnecessary (excluding CSS keyframes). For example: border: 1px 0px > border:1px 0

The code

function minifyCSS (css) {
    return String(css)
        .replace(/\/\*[\s\S]*?\*\//g, ' ') // Comments
        .replace(/\s+/g, ' ') // Extra spaces
        .replace(/([\(\)\{\}\:\;\,]) /g, '$1') // Extra spaces
        .replace(/ \{/g, '{') // Extra spaces
        .replace(/\;\}/g, '}') // Last semicolon
        .replace(/ ([+~>]) /g, '$1') // Extra spaces
        .replace(/([^{][,: \(\)]0)(%|px|pt|pc|rem|em|ex|cm|mm|in)([, };\(\)])/g, '$1$3') // Units for zero values
        .replace(/([: ,=\-\(])0\.(\d)/g, '$1.$2') // Lead zero for float values
        .replace(/([^\}]*\{\s*?\})/g, '') // Empty rules
        .replace(/([,: \(])#([0-9a-f]{6})/gi, function(m, pfx, clr) { // HEX code reducing
            if (clr[0] == clr[1] && clr[2] == clr[3] && clr[4] == clr[5]) return pfx + '#' + clr[0] + clr[2] + clr[4];
            return pfx + '#' + clr;
        });
 }

The deployment process will be different but there are lots of minifiers out there for javascript. I recommend using connect, then you can use this handy guy:

https://github.com/mape/connect-assetmanager

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top