From 8fbf4579a20c53fbf4ccbac765124313eab61397 Mon Sep 17 00:00:00 2001 From: Brad Cornes Date: Fri, 14 May 2021 11:08:17 +0100 Subject: [PATCH] Add support for PostCSS dependency messages --- plugins/plugin-postcss/plugin.js | 39 ++++++++++++++++++++++++++++++-- plugins/plugin-postcss/worker.js | 2 +- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/plugins/plugin-postcss/plugin.js b/plugins/plugin-postcss/plugin.js index bfb25f12ae..b539f37b22 100644 --- a/plugins/plugin-postcss/plugin.js +++ b/plugins/plugin-postcss/plugin.js @@ -1,6 +1,6 @@ 'use strict'; -const {resolve} = require('path'); +const {resolve, relative, isAbsolute} = require('path'); const workerpool = require('workerpool'); module.exports = function postcssPlugin(snowpackConfig, options) { @@ -14,6 +14,8 @@ module.exports = function postcssPlugin(snowpackConfig, options) { let worker, pool; + const dependencies = new Map(); + return { name: '@snowpack/postcss-transform', async transform({id, fileExt, contents}) { @@ -41,13 +43,46 @@ module.exports = function postcssPlugin(snowpackConfig, options) { } : false, }); - const {css, map} = JSON.parse(encodedResult); + const {css, map, messages} = JSON.parse(encodedResult); + + const files = new Set(); + const dirs = new Set(); + for (const message of messages) { + if (message.type === 'dependency') { + files.add(message.file); + } else if (message.type === 'dir-dependency') { + dirs.add(message.dir); + } + } + dependencies.set(id, {files, dirs}); + return { code: css, // old API (keep) contents: css, // new API map, }; }, + onChange({filePath}) { + eachId: for (const [id, {files, dirs}] of dependencies) { + for (const file of files) { + if (file === filePath) { + this.markChanged(id); + continue eachId; + } + } + for (const dir of dirs) { + // https://stackoverflow.com/a/45242825 + const relativePath = relative(dir, filePath); + const dirContainsFilePath = + relativePath && !relativePath.startsWith('..') && !isAbsolute(relativePath); + + if (dirContainsFilePath) { + this.markChanged(id); + continue eachId; + } + } + } + }, cleanup() { pool && pool.terminate(); }, diff --git a/plugins/plugin-postcss/worker.js b/plugins/plugin-postcss/worker.js index 55cbd6db10..110eca5043 100644 --- a/plugins/plugin-postcss/worker.js +++ b/plugins/plugin-postcss/worker.js @@ -15,7 +15,7 @@ async function transformAsync(css, {filepath, config, cwd, map}) { } const result = await process(css); - return JSON.stringify({css: result.css, map: result.map}); + return JSON.stringify({css: result.css, map: result.map, messages: result.messages}); } // create a worker and register public functions