Skip to content

Commit fd687cd

Browse files
committed
Ensure css-modulesify plays nice with watchify
Previously, CSS builds were only written out once and watchify would have to be restarted to trigger a new rebuild. This rewrites the CSS file on each call to `b.bundle()`, taking into account that watchify won't be re-transforming every CSS file every time.
1 parent aa36078 commit fd687cd

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

index.js

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,17 @@ module.exports = function (browserify, options) {
1313
throw new Error('css-modulesify needs the --output / -o option (path to output css file)');
1414
}
1515

16-
var cssOut = through();
17-
cssOut.pipe(fs.createWriteStream(cssOutFilename));
18-
1916
// keep track of css files visited
2017
var filenames = [];
2118

2219
// keep track of all tokens so we can avoid duplicates
2320
var tokensByFile = {};
2421

22+
// keep track of all source files for later builds: when
23+
// using watchify, not all files will be caught on subsequent
24+
// bundles
25+
var sourceByFile = {};
26+
2527
browserify.transform(function transform (filename) {
2628
// only handle .css files
2729
if (!cssExt.test(filename)) {
@@ -43,7 +45,9 @@ module.exports = function (browserify, options) {
4345
var output = "module.exports = " + JSON.stringify(tokens);
4446

4547
assign(tokensByFile, loader.tokensByFile);
46-
cssOut.queue(loader.finalSource);
48+
49+
// store this file's source to be written out to disk later
50+
sourceByFile[filename] = loader.finalSource;
4751

4852
self.queue(output);
4953
self.queue(null);
@@ -56,13 +60,22 @@ module.exports = function (browserify, options) {
5660
// wrap the `bundle` function
5761
var bundle = browserify.bundle;
5862
browserify.bundle = function (opts, cb) {
63+
// reset the `tokensByFile` cache
64+
tokensByFile = {};
5965

6066
// call the original
6167
var stream = bundle.apply(browserify, arguments);
6268

6369
// close the css stream
6470
stream.on('end', function () {
65-
cssOut.queue(null);
71+
// Combine the collected sources into a single CSS file
72+
var css = Object.keys(sourceByFile).map(function(file) {
73+
return sourceByFile[file];
74+
}).join('\n');
75+
76+
fs.writeFile(cssOutFilename, css, function(err) {
77+
console.error(err);
78+
});
6679
});
6780

6881
return stream;

0 commit comments

Comments
 (0)