From 81f7551011a52187f8b185f375ae1c5c5ac190d5 Mon Sep 17 00:00:00 2001 From: Jay Harris Date: Wed, 7 Sep 2022 16:55:26 +1200 Subject: [PATCH] Add plugin for forking CSS to a file. This makes it usable without JavaScript --- postcss/fork-css.js | 26 ++++++++++++++++++++++++++ rollup.config.js | 8 +++++++- 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 postcss/fork-css.js diff --git a/postcss/fork-css.js b/postcss/fork-css.js new file mode 100644 index 000000000..27a064b7c --- /dev/null +++ b/postcss/fork-css.js @@ -0,0 +1,26 @@ +const fs = require('fs') +const path = require('path') + +const getInputPath = (root) => root.source.input.file + +module.exports = (options = { outputFolder: 'build', match: /^((?!\.(stories|test)).)*\.svelte/gi, dropExtension: true }) => { + const getOutputFile = (inputFile) => { + const fileName = path.basename(inputFile, options.dropExtension ? path.extname(inputFile) : undefined); + const relativePath = path.relative('.', path.resolve(inputFile, '..')) + return path.join(options.outputFolder, relativePath, fileName + '.css'); + } + + return { + postcssPlugin: 'fork-css', + OnceExit: (root) => { + const inputFile = getInputPath(root); + if (!options.match.test(inputFile)) return; + + const outputFile = getOutputFile(inputFile); + fs.mkdirSync(path.dirname(outputFile), { recursive: true }); + fs.writeFileSync(outputFile, root.toString()); + } + } +} + +module.exports.postcss = true; diff --git a/rollup.config.js b/rollup.config.js index 139f08941..34f2d0d14 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -25,7 +25,13 @@ export default { plugins: [ svelteTypes(), svelte({ - preprocess: sveltePreprocess(), + preprocess: sveltePreprocess({ + postcss: { + plugins: [ + require('./postcss/fork-css') + ] + } + }), compilerOptions: { customElement: true },