From e60f6a7b2713ceca22b59a6f70212cd324ea4dbe Mon Sep 17 00:00:00 2001 From: Andrew Joslin Date: Sat, 19 Mar 2016 17:51:19 -0700 Subject: [PATCH] Use writeFileSync to write to out file Using a write stream, the target file would be erased each time css-extract started. This meant that, when using livereload with CSS, there were two visible reloads: once at the start of css-extract, and once when it finished. Using writeFileSync, the file is only edited once in place. --- index.js | 7 ++++++- package.json | 4 +++- test/index.js | 25 +++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 59432f8..276f6da 100644 --- a/index.js +++ b/index.js @@ -1,3 +1,4 @@ +const ConcatStream = require('concat-stream') const isRequire = require('is-require')() const through = require('through2') const falafel = require('falafel') @@ -25,7 +26,7 @@ function cssExtract (bundle, opts) { bundle.pipeline.get('debug').unshift(through.obj(write, flush)) const writeStream = (typeof outFile === 'function') ? outFile() - : fs.createWriteStream(outFile) + : ConcatStream(writeOutFile) function write (chunk, enc, cb) { const css = extract(chunk) @@ -39,6 +40,10 @@ function cssExtract (bundle, opts) { cb() } } + + function writeOutFile (buffer) { + fs.writeFileSync(outFile, buffer) + } } // extract css from chunks diff --git a/package.json b/package.json index 312ebe7..2a4429f 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ ], "license": "MIT", "dependencies": { + "concat-stream": "^1.5.1", "falafel": "^1.2.0", "is-require": "0.0.1", "through2": "^2.0.1" @@ -32,7 +33,8 @@ "istanbul": "^0.4.2", "sheetify": "^4.1.0", "standard": "^6.0.7", - "tape": "^4.5.0" + "tape": "^4.5.0", + "tmp": "0.0.28" }, "files": [ "index.js", diff --git a/test/index.js b/test/index.js index 9d1736f..c614c9a 100644 --- a/test/index.js +++ b/test/index.js @@ -1,4 +1,5 @@ const browserify = require('browserify') +const tmpDir = require('tmp').dir const path = require('path') const test = require('tape') const bl = require('bl') @@ -29,4 +30,28 @@ test('css-extract', function (t) { }) } }) + + t.test('should write file', function (t) { + t.plan(3) + tmpDir({unsafeCleanup: true}, onDir) + + function onDir (err, dir, cleanup) { + t.ifError(err, 'no error') + const outFile = path.join(dir, 'out.css') + + browserify(path.join(__dirname, 'source.js')) + .transform('sheetify/transform') + .plugin(cssExtract, { out: outFile }) + .bundle(function (err) { + t.ifError(err, 'no bundle error') + + const exPath = path.join(__dirname, './expected.css') + const expected = fs.readFileSync(exPath, 'utf8').trim() + const actual = fs.readFileSync(outFile, 'utf8').trim() + t.equal(expected, actual, 'all css written to file') + + cleanup() + }) + } + }) })