Add vite plugin

This commit is contained in:
Alex
2024-03-30 21:26:11 -04:00
parent 8f6e77f899
commit dbfdf67983
3 changed files with 36 additions and 4 deletions

View File

@ -3,13 +3,15 @@ import { basename, dirname, extname, join } from "node:path";
import { once } from "lodash";
import hash from "@emotion/hash";
import type babel from "@babel/core";
import { type NodePath, type types as t, transformSync } from "@babel/core";
import type * as vite from "vite";
import type * as esbuild from "esbuild";
import { type NodePath, type types as t, transformSync } from "@babel/core";
import tailwind, { type Config } from "tailwindcss";
import postcss from "postcss";
const PLUGIN_NAME = "tailwind";
const ESBUILD_NAMESPACE = "babel-tailwind";
const ROLLUP_PREFIX = "\0tailwind:";
const definePlugin =
<T>(fn: (runtime: typeof babel) => babel.Visitor<babel.PluginPass & T>) =>
@ -132,6 +134,7 @@ const babelTailwind = (
const result = Array.from(tailwindMap)
.map(([className, value]) => `.${className} {\n @apply ${value}\n}`)
.join("\n");
styleMap.set(join(dirname(filename), cssName), result);
},
},
@ -301,9 +304,33 @@ const esbuildPlugin = (
},
});
const vitePlugin = (styleMap: Map<string, string>, compile: Compile): vite.Plugin => ({
name: "tailwind",
resolveId(id, importer) {
if (id.startsWith("tailwind:")) {
const resolved = join(dirname(importer!), id.slice("tailwind:".length));
if (styleMap.has(resolved)) {
return {
id: ROLLUP_PREFIX + resolved,
moduleSideEffects: true,
};
}
}
},
async load(id: string) {
if (id.startsWith(ROLLUP_PREFIX)) {
const resolved = id.slice(ROLLUP_PREFIX.length);
if (styleMap.has(resolved)) {
const result = await compile(styleMap.get(resolved)!);
return result.css;
}
}
},
});
/**
* Main entry. Returns the esbuild, babel plugins and utilities for processing
* Tailwind classNames in JS.
* Main entry. Returns the plugins and utilities for processing Tailwind
* classNames in JS.
*
* @example
* import { build } from "esbuild";
@ -325,6 +352,7 @@ export function getTailwindPlugins(options: TailwindPluginOptions) {
compile,
babel: babelTailwind(styleMap, options),
esbuild: esbuildPlugin(styleMap, compile),
vite: vitePlugin(styleMap, compile),
styleMap,
[Symbol.dispose]() {
styleMap.clear();