63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
import { dirname, join } from "node:path";
|
|
import type * as vite from "vite";
|
|
import { type Compile, type StyleMap, macroNames, pkgName } from "./shared";
|
|
import type { BuildStyleFile } from "./index";
|
|
|
|
const ROLLUP_PREFIX = "\0tailwind:";
|
|
|
|
export const vitePlugin = ({
|
|
styleMap,
|
|
compile,
|
|
buildStyleFile,
|
|
}: {
|
|
styleMap: StyleMap;
|
|
compile: Compile;
|
|
buildStyleFile: BuildStyleFile;
|
|
}): vite.Plugin => ({
|
|
name: "tailwind",
|
|
|
|
config(config) {
|
|
((config.optimizeDeps ??= {}).exclude ??= []).push(...macroNames, `${pkgName}/base`);
|
|
},
|
|
|
|
resolveId(id, importer) {
|
|
if (id === `${pkgName}/base`) {
|
|
return {
|
|
id: ROLLUP_PREFIX + "directive:base",
|
|
moduleSideEffects: true,
|
|
};
|
|
}
|
|
|
|
if (id.startsWith("tailwind:")) {
|
|
const [name, cacheKey] = id.slice("tailwind:".length).split("?");
|
|
const resolved = join(dirname(importer!), name);
|
|
if (styleMap.has(resolved)) {
|
|
return {
|
|
id: ROLLUP_PREFIX + resolved + "?" + cacheKey,
|
|
moduleSideEffects: true,
|
|
};
|
|
}
|
|
}
|
|
},
|
|
|
|
async load(id: string) {
|
|
if (id.startsWith(ROLLUP_PREFIX)) {
|
|
const resolved = id.slice(ROLLUP_PREFIX.length);
|
|
if (resolved === "directive:base") {
|
|
return await compile("@tailwind base");
|
|
}
|
|
|
|
const name = resolved.split("?")[0];
|
|
if (styleMap.has(name)) {
|
|
return (await buildStyleFile(name))[1];
|
|
}
|
|
}
|
|
},
|
|
});
|
|
|
|
/**
|
|
* `babel-plugin-macros` compatible `isMacrosName` function that works with this plugin.
|
|
*/
|
|
export const isMacrosName = (v: string) =>
|
|
!macroNames.includes(v) && /[./]macro(\.c?js)?$/.test(v);
|