Search code examples
browserify

Is there a way to build a master css file based on required css in javascript components using browserify?


Let's say I have modules similar to this one:

"use strict";

var moduleCss = require("module1.css");
var template = require("module1.hmtl");

module.exports = function(){
   //my module code here
};

And another one with a different css file.

"use strict";

var moduleCss = require("module2.css");
var template = require("module2.hmtl");

module.exports = function(){
   //my module code here
};

The main file would look like this:

"use strict";

var module1 = require("module1");
var module2 = require("module2");
var normalize = require("normalize.css");
var bootstrap = require("bootstrap.css"); 

module.exports = function(){
   //my module code here
};

Instead of appending each css file content as a style tag, i'd like to get a main.css when building the main bundle by looking at each required css file in each module and building a single CSS file containing all the styles in all required modules so that I can append this single css file where I want.

I'm basically trying to have the css requirements in the same spot as the js and html requirements. The solutions that I found so far require a different CSS file that keeps track of each module css dependency, so adding or removing a module in my applications requires work in 2 files, the main js and the main css.

Is there a way to achieve this? To have ALL dependencies into one file? Or could a "package.json" thingy be used for each module where the CSS dependencies could be declared?


Solution

  • After playing around a little bit with browserify it turned out the transform function hook reveals the file name of each required file. I basically looked for css and less file, return a empty module for them, and kept each file in a reference array.

    After the bundle was done, by listening to the bundle event, I created a string where I basically "included" each file that I captured in the reference array.

    With the import file created, I simply passed it to the less compiler.

    Here's a link to the gist for my current task : https://gist.github.com/vladnicula/fd1ff7b30ef20789e1dc