From a2a359af36255d464e9fe79eb720d5c470eac9d6 Mon Sep 17 00:00:00 2001 From: Rogelio Guzman Date: Tue, 28 Nov 2017 12:54:25 -0800 Subject: [PATCH] Do not rewrite files when content did not change --- .../__test__/index.test.js | 44 +++++++++++++++++++ .../css-modules-flow-types-loader/index.js | 15 ++++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/packages/css-modules-flow-types-loader/__test__/index.test.js b/packages/css-modules-flow-types-loader/__test__/index.test.js index f54f3be..be92f2d 100644 --- a/packages/css-modules-flow-types-loader/__test__/index.test.js +++ b/packages/css-modules-flow-types-loader/__test__/index.test.js @@ -69,6 +69,50 @@ declare module.exports: {| `${HEADER} declare module.exports: {| +|}; +` + ); + }); + + it('does not emit a css.flow file if the file exists and has the same contents', () => { + fs.existsSync.mockImplementationOnce( + filePath => filePath === 'test.css.flow' + ); + + loader.call( + { + resourcePath: 'test.css', + }, + STYLE_LOADER_OUTPUT + ); + + expect(fs.writeFile.mock.calls.length).toBe(0); + }); + + it('emits a css.flow file if the file exists and has the different contents', () => { + fs.existsSync.mockImplementationOnce( + filePath => filePath === 'test.css.flow' + ); + + fs.readFile.mockImplementationOnce((filePath, opts, cb) => { + if (filePath === 'test.css.flow') { + cb(null, 'Other content'); + } + }); + loader.call( + { + resourcePath: 'test.css', + }, + STYLE_LOADER_OUTPUT + ); + + expect(fs.writeFile.mock.calls.length).toBe(1); + expect(fs.writeFile.mock.calls[0][0]).toBe('test.css.flow'); + + expect(fs.writeFile.mock.calls[0][1]).toBe( + `${HEADER} +declare module.exports: {| + +'btn': string; |}; ` ); diff --git a/packages/css-modules-flow-types-loader/index.js b/packages/css-modules-flow-types-loader/index.js index 084a066..59f3916 100644 --- a/packages/css-modules-flow-types-loader/index.js +++ b/packages/css-modules-flow-types-loader/index.js @@ -25,7 +25,20 @@ module.exports = function cssModulesFlowTypesLoader(content) { // NOTE: We cannot use .emitFile as people might use this with devServer // (e.g. in memory storage). const outputPath = this.resourcePath + '.flow'; - fs.writeFile(outputPath, printFlowDefinition(tokens), {}, function() {}); + const newContent = printFlowDefinition(tokens); + if (fs.existsSync(outputPath)) { + fs.readFile(outputPath, 'utf8', function(err, currentContent) { + if (err) { + throw err; + } + + if (currentContent !== newContent) { + fs.writeFile(outputPath, newContent, {}, function() {}); + } + }); + } else { + fs.writeFile(outputPath, newContent, {}, function() {}); + } return content; };