From 807b588afcb80aee946479ea77d269b2f59a1af9 Mon Sep 17 00:00:00 2001 From: Andrey Grandilevskiy Date: Mon, 20 Jun 2022 15:57:16 +0200 Subject: [PATCH] Enable hot reloading of the functional mixins (#146) * Enable hot reloading of the functional mixins * Update tests: add dependency case --- index.js | 21 ++++++++++++++++++++- test/deps/f.js | 1 + test/deps/g.js | 3 +++ test/index.test.js | 25 +++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 test/deps/f.js create mode 100644 test/deps/g.js diff --git a/index.js b/index.js index dab93fe..0fdc5cc 100644 --- a/index.js +++ b/index.js @@ -33,6 +33,19 @@ function addMixin(helpers, mixins, rule, file) { rule.remove() } +function processModulesForHotReloadRecursively(module, helpers) { + let moduleId = module.id + module.children.forEach(childModule => { + helpers.result.messages.push({ + type: 'dependency', + file: childModule.id, + parent: moduleId + }) + processModulesForHotReloadRecursively(childModule, helpers) + }) + delete require.cache[moduleId] +} + function loadGlobalMixin(helpers, globs) { let cwd = process.cwd() let files = glob.sync(globs, { caseSensitiveMatch: IS_WIN }) @@ -53,7 +66,13 @@ function loadGlobalMixin(helpers, globs) { addMixin(helpers, mixins, atrule, path) }) } else { - mixins[name] = { mixin: require(path), file: path } + try { + mixins[name] = { mixin: require(path), file: path } + let module = require.cache[require.resolve(path)] + if (module) { + processModulesForHotReloadRecursively(module, helpers) + } + } catch {} } }) return mixins diff --git a/test/deps/f.js b/test/deps/f.js new file mode 100644 index 0000000..e2e86a7 --- /dev/null +++ b/test/deps/f.js @@ -0,0 +1 @@ +module.exports = require('./g') diff --git a/test/deps/g.js b/test/deps/g.js new file mode 100644 index 0000000..78f69a9 --- /dev/null +++ b/test/deps/g.js @@ -0,0 +1,3 @@ +module.exports = { + g: '5' +} diff --git a/test/index.test.js b/test/index.test.js index 6706a28..ba13748 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -341,6 +341,31 @@ test('loads mixins from file globs', async () => { }) }) +test('loads mixins with dependencies', async () => { + let result = await run( + 'a { @mixin f; }', + 'a { g: 5; }', + { + mixinsFiles: join(__dirname, 'deps', 'f.js') + } + ) + equal( + result.messages.sort((a, b) => a.file && a.file.localeCompare(b.file)), + [ + { + file: join(__dirname, 'deps/f.js'), + type: 'dependency', + parent: '' + }, + { + file: join(__dirname, 'deps/g.js'), + type: 'dependency', + parent: join(__dirname, 'deps/f.js') + } + ] + ) +}) + test('coverts mixins values', async () => { let processor = postcss( mixins({