Skip to content

Instantly share code, notes, and snippets.

@bluwy
Created December 13, 2020 05:48
Show Gist options
  • Save bluwy/69274260fcd3a12269ed6f3c0864d4c0 to your computer and use it in GitHub Desktop.
Save bluwy/69274260fcd3a12269ed6f3c0864d4c0 to your computer and use it in GitHub Desktop.
Rollup plugin to transform postcss files to virtual css files. Can be used with rollup-plugin-css-only to build a single css bundle
import { createFilter } from '@rollup/pluginutils'
import postcss from 'postcss'
import loadConfig from 'postcss-load-config'
/**
* @typedef {{
* include: import('@rollup/pluginutils').FilterPattern,
* exclude: import('@rollup/pluginutils').FilterPattern
* }} Options
*/
/**
* Load postcss files and emit them as virtual css files
* @param {Options} options
* @returns {import('rollup').Plugin}
*/
export default function (options = {}) {
const filter = createFilter(options.include || '**/*.pcss', options.exclude)
const emitCache = new Map()
return {
name: 'postcss',
resolveId(importee) {
if (emitCache.has(importee)) return importee
},
load(id) {
if (emitCache.has(id)) return emitCache.get(id) || ''
},
async transform(code, id) {
if (!filter(id)) return
const config = await loadConfig()
const result = await postcss(config.plugins).process(code, { from: id })
for (const warning of result.warnings()) {
this.warn(warning.message || warning.text)
}
// Convert extension to .css
const idWithCss = id.substring(0, id.lastIndexOf('.')) + '.css'
// TODO: Support sourcemaps
emitCache.set(idWithCss, result.css)
return `import ${JSON.stringify(idWithCss)}`
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment