Dennis Nerush
Dennis Nerush

Reputation: 5663

Combine CSS files into single file using NPM

I have several css files in my project. I want to combine them into a single one only via NPM (no gulp or grunt).

I heard of ccs-merge and other node modules but didn't see any practical example. What is the best and the easiest way to achieve it?

Edited:

Here is my project structure:

Client/
     ├──js/
         |──component1  
               ├──one.css 
               ├──one.js 
         |──component2  
               ├──two.css 
               ├──two.js 
    ├──output/
    └──package.json

I want to combine all my CSS files into a single file directly from the NPM script. Here is my current package.json

"scripts": {
    "start": "watchify -o Client/js/bundle.js -v -d Client/js/app.jsx",
    "build": "browserify . -t [envify --NODE_ENV production] | uglifyjs  -cm > Client/js/bundle.min.js",
    "concat-css": "css-concat  Client/js/*.css > Client/js/styles.css"
  },

The concat-css command doesn't work. "Failed at.... 'css-concat...'

Upvotes: 16

Views: 9467

Answers (1)

superEb
superEb

Reputation: 5673

Here's the simplest example I could think of. Given the following project structure and files:

project/
├──css/
|  ├──one.css
|  └──two.css
├──output/
└──package.json

project/css/one.css:

.one {
  color: red;
}

project/css/two.css:

.two {
  text-align: center;
}

project/package.json:

{
  "name": "project",
  "version": "1.0.0",
  "scripts": {
    "concat-css": "cat css/* > output/all.css"
  }
}

You can run this in your terminal:

$ npm run concat-css

> [email protected] concat-css /path/to/project
> cat css/* > output/all.css

Which results in project/output/all.css:

.one {
  color: red;
}
.two {
  text-align: center;
}

This is obviously overly simplistic, but it should demonstrate the concept. You can pipe multiple shell commands together via npm run scripts, and you can even call run scripts from within other run scripts.

Here's a very good article about this topic by Keith Cirkel (No grunt or gulp needed.)

Upvotes: 14

Related Questions