astro/packages/integrations/tailwind/src/index.ts
Fred K. Bot acd0b6da3c
[ci] update lockfile (#4100)
* [ci] update lockfile

* fix: remove @ts-expect-error

Co-authored-by: FredKSchott <FredKSchott@users.noreply.github.com>
Co-authored-by: Nate Moore <nate@astro.build>
2022-08-03 11:16:07 -05:00

82 lines
2.6 KiB
TypeScript

import load from '@proload/core';
import type { AstroIntegration } from 'astro';
import autoprefixerPlugin from 'autoprefixer';
import path from 'path';
import tailwindPlugin, { Config as TailwindConfig } from 'tailwindcss';
import resolveConfig from 'tailwindcss/resolveConfig.js';
import { fileURLToPath } from 'url';
function getDefaultTailwindConfig(srcUrl: URL): TailwindConfig {
return resolveConfig({
theme: {
extend: {},
},
plugins: [],
content: [path.join(fileURLToPath(srcUrl), `**`, `*.{astro,html,js,jsx,svelte,ts,tsx,vue}`)],
presets: undefined, // enable Tailwind's default preset
}) as TailwindConfig;
}
async function getUserConfig(root: URL, configPath?: string) {
const resolvedRoot = fileURLToPath(root);
let userConfigPath: string | undefined;
if (configPath) {
const configPathWithLeadingSlash = /^\.*\//.test(configPath) ? configPath : `./${configPath}`;
userConfigPath = fileURLToPath(new URL(configPathWithLeadingSlash, root));
}
return await load('tailwind', { mustExist: false, cwd: resolvedRoot, filePath: userConfigPath });
}
type TailwindOptions =
| {
config?: {
/**
* Path to your tailwind config file
* @default 'tailwind.config.js'
*/
path?: string;
/**
* Apply Tailwind's base styles
* Disabling this is useful when further customization of Tailwind styles
* and directives is required. See {@link https://tailwindcss.com/docs/functions-and-directives#tailwind Tailwind's docs}
* for more details on directives and customization.
* @default: true
*/
applyBaseStyles?: boolean;
};
}
| undefined;
export default function tailwindIntegration(options?: TailwindOptions): AstroIntegration {
const applyBaseStyles = options?.config?.applyBaseStyles ?? true;
const customConfigPath = options?.config?.path;
return {
name: '@astrojs/tailwind',
hooks: {
'astro:config:setup': async ({ config, injectScript }) => {
// Inject the Tailwind postcss plugin
const userConfig = await getUserConfig(config.root, customConfigPath);
if (customConfigPath && !userConfig?.value) {
throw new Error(
`Could not find a Tailwind config at ${JSON.stringify(
customConfigPath
)}. Does the file exist?`
);
}
const tailwindConfig: TailwindConfig =
(userConfig?.value as TailwindConfig) ?? getDefaultTailwindConfig(config.srcDir);
config.style.postcss.plugins.push(tailwindPlugin(tailwindConfig));
config.style.postcss.plugins.push(autoprefixerPlugin);
if (applyBaseStyles) {
// Inject the Tailwind base import
injectScript('page-ssr', `import '@astrojs/tailwind/base.css';`);
}
},
},
};
}