Skip to content

Instantly share code, notes, and snippets.

@astahmer
Created December 2, 2023 14:46
Show Gist options
  • Save astahmer/caa416cf39fd49b50992e3ef01a1921f to your computer and use it in GitHub Desktop.
Save astahmer/caa416cf39fd49b50992e3ef01a1921f to your computer and use it in GitHub Desktop.
Panda CSS vite plugin to inline `css` result as class strings
import { PandaContext, loadConfigAndCreateContext } from '@pandacss/node'
import { createCss } from '@pandacss/shared'
import { isAbsolute, resolve } from 'path'
import { PluginOption, ResolvedConfig, createFilter } from 'vite'
import MagicString from 'magic-string'
const ensureAbsolute = (path: string, root: string) => (path ? (isAbsolute(path) ? path : resolve(root, path)) : root)
const pandaVite = (): PluginOption => {
let config: ResolvedConfig
let root: string
let panda: PandaContext
let isIncluded: ReturnType<typeof createFilter>
return {
name: 'panda',
enforce: 'pre',
async configResolved(resolvedConfig) {
config = resolvedConfig
root = ensureAbsolute('', resolvedConfig.root)
panda = await loadConfigAndCreateContext()
isIncluded = createFilter(panda.config.include ?? /\.[jt]sx?$/, panda.config.exclude ?? [/node_modules/], {
resolve: root,
})
// console.log(panda.config)
},
transform(code, id) {
if (!isIncluded(id)) return null
// const sourceFile = panda.project.getSourceFile(id)
// if (!sourceFile) return null
// console.log({ id, sourceFile: sourceFile.getText().length })
panda.project.addSourceFile(id, code)
const parserResult = panda.project.parseSourceFile(id)
console.log({ id }, parserResult)
if (!parserResult) return null
const sourceFile = panda.project.getSourceFile(id)
if (!sourceFile) return null
const magicStr = new MagicString(code)
const css = createCss(panda.createSheetContext())
parserResult.all.forEach((result) => {
if (result.type === 'object') {
const classList = new Set<string>()
result.data.map((data) => {
classList.add(css(data))
})
const node = result.box.getNode()
magicStr.update(node.getStart(), node.getEnd(), `"${Array.from(classList).join(' ')}"`)
return
}
if (result.type === 'cva') {
//
}
if (result.type === 'jsx') {
//
}
})
return {
code: magicStr.toString(),
map: magicStr.generateMap({ hires: true }),
}
},
}
}
export default pandaVite
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment