vite-plugin-tailwind-ref 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 awaiden
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,225 @@
1
+ # vite-plugin-tailwind-ref
2
+
3
+ A Vite plugin that automatically adds `@reference` directives to CSS files using Tailwind CSS `@apply`, enabling utility class usage without manual imports.
4
+
5
+ ## Problem
6
+
7
+ When using Tailwind's `@apply` directive in CSS files (including framework-scoped styles like Svelte or Vue components), you typically need to manually add `@reference` directives:
8
+
9
+ ```css
10
+ @reference "tailwindcss";
11
+
12
+ .my-class {
13
+ @apply flex items-center;
14
+ }
15
+ ```
16
+
17
+ This is repetitive and easy to forget.
18
+
19
+ ## Solution
20
+
21
+ This plugin automatically injects the necessary `@reference` directive when it detects `@apply` usage in your CSS files.
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install -D vite-plugin-tailwind-ref
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ Add the plugin to your `vite.config.ts`:
32
+
33
+ ```typescript
34
+ import { defineConfig } from "vite";
35
+ import tailwindAutoReference from "vite-plugin-tailwind-ref";
36
+
37
+ export default defineConfig({
38
+ plugins: [tailwindAutoReference()],
39
+ });
40
+ ```
41
+
42
+ Now you can use `@apply` in your CSS files without manually adding `@reference` directives:
43
+
44
+ ```css
45
+ .my-class {
46
+ @apply flex items-center justify-center;
47
+ }
48
+ ```
49
+
50
+ The plugin will automatically inject:
51
+
52
+ ```css
53
+ @reference "tailwindcss";
54
+
55
+ .my-class {
56
+ @apply flex items-center justify-center;
57
+ }
58
+ ```
59
+
60
+ ### Svelte
61
+
62
+ For Svelte component style blocks, configure the `include` pattern to match Svelte's style query:
63
+
64
+ ```typescript
65
+ // vite.config.ts
66
+ import { defineConfig } from "vite";
67
+ import { svelte } from "@sveltejs/vite-plugin-svelte";
68
+ import tailwindAutoReference from "vite-plugin-tailwind-ref";
69
+
70
+ export default defineConfig({
71
+ plugins: [
72
+ svelte(),
73
+ tailwindAutoReference("tailwindcss", {
74
+ include: [/\.svelte\?.*svelte&type=style/],
75
+ }),
76
+ ],
77
+ });
78
+ ```
79
+
80
+ Then use `@apply` freely in your components:
81
+
82
+ ```svelte
83
+ <style>
84
+ .my-class {
85
+ @apply flex items-center justify-center;
86
+ }
87
+ </style>
88
+ ```
89
+
90
+ ### Vue
91
+
92
+ For Vue component style blocks, match Vue's style query:
93
+
94
+ ```typescript
95
+ // vite.config.ts
96
+ import { defineConfig } from "vite";
97
+ import vue from "@vitejs/plugin-vue";
98
+ import tailwindAutoReference from "vite-plugin-tailwind-ref";
99
+
100
+ export default defineConfig({
101
+ plugins: [
102
+ vue(),
103
+ tailwindAutoReference("tailwindcss", {
104
+ include: [/\.vue\?.*type=style/],
105
+ }),
106
+ ],
107
+ });
108
+ ```
109
+
110
+ Then use `@apply` in your components:
111
+
112
+ ```vue
113
+ <style scoped>
114
+ .my-class {
115
+ @apply flex items-center justify-center;
116
+ }
117
+ </style>
118
+ ```
119
+
120
+ ### Multiple frameworks / CSS files together
121
+
122
+ You can combine multiple patterns to cover both standalone CSS files and framework style blocks:
123
+
124
+ ```typescript
125
+ tailwindAutoReference("tailwindcss", {
126
+ include: [/\.css$/, /\.svelte\?.*svelte&type=style/],
127
+ });
128
+ ```
129
+
130
+ ## Configuration
131
+
132
+ ### Basic Options
133
+
134
+ ```typescript
135
+ tailwindAutoReference(cssFile, options);
136
+ ```
137
+
138
+ #### `cssFile` (optional)
139
+
140
+ Type: `string | string[] | (code?: string, id?: string) => string | string[] | Promise<string | string[]>`
141
+ Default: `"tailwindcss"`
142
+
143
+ The path(s) to your Tailwind CSS file, or a function that returns the path(s).
144
+
145
+ **Examples:**
146
+
147
+ ```typescript
148
+ // String path
149
+ tailwindAutoReference("./src/styles/tailwind.css");
150
+
151
+ // Multiple paths
152
+ tailwindAutoReference(["./src/styles/tailwind.css", "./src/styles/custom.css"]);
153
+
154
+ // Dynamic function
155
+ tailwindAutoReference((code, id) => {
156
+ return id.includes("admin") ? "./admin-tailwind.css" : "./tailwind.css";
157
+ });
158
+
159
+ // Async function
160
+ tailwindAutoReference(async (code, id) => {
161
+ const config = await loadConfig();
162
+ return config.cssPath;
163
+ });
164
+ ```
165
+
166
+ #### `options` (optional)
167
+
168
+ Type: `object`
169
+
170
+ - **`include`** (optional)
171
+ Type: `FilterPattern` (string | RegExp | Array<string | RegExp>)
172
+ Default: `[/\.css$/]`
173
+ Patterns to match files for transformation.
174
+
175
+ - **`exclude`** (optional)
176
+ Type: `FilterPattern`
177
+ Default: `[]`
178
+ Patterns to exclude from transformation.
179
+
180
+ - **`skip`** (optional)
181
+ Type: `(code?: string, id?: string) => boolean`
182
+ Default: `() => false`
183
+ Custom function to skip transformation based on file content or path.
184
+
185
+ ### Advanced Examples
186
+
187
+ ```typescript
188
+ // Custom include/exclude patterns
189
+ tailwindAutoReference("./src/styles/tailwind.css", {
190
+ include: [/\.css$/, /\.svelte\?.*svelte&type=style/],
191
+ exclude: [/node_modules/],
192
+ });
193
+
194
+ // Skip specific files
195
+ tailwindAutoReference("./src/styles/tailwind.css", {
196
+ skip: (code, id) => {
197
+ return code?.includes("@reference") ?? false;
198
+ },
199
+ });
200
+ ```
201
+
202
+ ## How It Works
203
+
204
+ 1. The plugin runs in Vite's `pre` enforce phase
205
+ 2. It intercepts CSS files (or files matching the configured `include` pattern)
206
+ 3. When it detects `@apply` usage, it injects the `@reference` directive
207
+ 4. If `@use` statements exist, the `@reference` is placed after the last `@use`
208
+ 5. Otherwise, it's placed at the beginning of the file
209
+ 6. Files that already contain `@reference` or `@import "tailwindcss"` are skipped
210
+
211
+ ## Requirements
212
+
213
+ - Vite 5.x, 6.x, 7.x, or 8.x
214
+
215
+ ## Credits
216
+
217
+ This plugin is inspired by [vite-plugin-vue-tailwind-auto-reference](https://github.com/M1CK431/vite-plugin-vue-tailwind-auto-reference) by M1CK431.
218
+
219
+ ## License
220
+
221
+ MIT
222
+
223
+ ## Contributing
224
+
225
+ Issues and pull requests are welcome at [https://github.com/awaiden/vite-plugin-tailwind-ref](https://github.com/awaiden/vite-plugin-tailwind-ref)
@@ -0,0 +1,33 @@
1
+ import { FilterPattern, Plugin } from "vite";
2
+
3
+ //#region src/index.d.ts
4
+ /**
5
+ * A callback that determines which "@reference" should be added by the tailwindAutoReference plugin.
6
+ * Returns the path to the Tailwind CSS file or an array of them.
7
+ */
8
+ type CssFileFn = (code?: string, id?: string) => Promise<string | string[]> | string | string[];
9
+ /**
10
+ * An options object for the tailwindAutoReference plugin.
11
+ */
12
+ interface PluginOption {
13
+ /** A list of picomatch patterns that match files to be excluded from transformation */
14
+ exclude?: FilterPattern;
15
+ /** A list of picomatch patterns that match files to be transformed */
16
+ include?: FilterPattern;
17
+ /** A function that determines whether a file should be skipped */
18
+ skip: SkipFn;
19
+ }
20
+ /**
21
+ * A callback that determines whether a file should be skipped by the tailwindAutoReference plugin.
22
+ * Returns true if the file should be skipped, false otherwise.
23
+ */
24
+ type SkipFn = (code?: string, id?: string) => boolean;
25
+ /**
26
+ * A Vite plugin that automatically adds "@reference" directives to CSS files using @apply.
27
+ *
28
+ * @param cssFile - The path to the Tailwind CSS file or an array of them or a sync or async function that returns it or them.
29
+ * @param opts - An options object for configuring the plugin behavior.
30
+ */
31
+ declare const tailwindAutoReference: (cssFile?: CssFileFn | string | string[], opts?: PluginOption) => Plugin;
32
+ //#endregion
33
+ export { tailwindAutoReference as default };
package/dist/index.mjs ADDED
@@ -0,0 +1,49 @@
1
+ import { resolve } from "node:path";
2
+ import { createFilter } from "vite";
3
+ //#region src/index.ts
4
+ const defaultOpts = {
5
+ exclude: [],
6
+ include: [/\.css$/],
7
+ skip: () => false
8
+ };
9
+ const resolveFn = (fn, ...args) => Promise.resolve(fn instanceof Function ? fn(args) : fn);
10
+ /**
11
+ * A Vite plugin that automatically adds "@reference" directives to CSS files using @apply.
12
+ *
13
+ * @param cssFile - The path to the Tailwind CSS file or an array of them or a sync or async function that returns it or them.
14
+ * @param opts - An options object for configuring the plugin behavior.
15
+ */
16
+ const tailwindAutoReference = (cssFile = "tailwindcss", opts = defaultOpts) => {
17
+ const { exclude, include, skip } = {
18
+ ...defaultOpts,
19
+ ...opts
20
+ };
21
+ let fileFilter, root;
22
+ const getReferenceStr = (reference) => (Array.isArray(reference) ? reference : [reference]).reduce((acc, file) => `${acc}\n@reference "${resolve(root, file)}";`, "");
23
+ return {
24
+ configResolved: (config) => {
25
+ root = config.root;
26
+ fileFilter = createFilter(include, exclude, { resolve: root });
27
+ },
28
+ enforce: "pre",
29
+ name: "tailwind-auto-reference",
30
+ transform: async (code, id) => {
31
+ if (!fileFilter(id)) return null;
32
+ if (!code.includes("@apply ") || skip(code, id)) return null;
33
+ if (code.includes("@reference ") || code.includes("@import \"tailwindcss\"")) return null;
34
+ const lastUseMatch = [...code.matchAll(/^\s*@use.*\n/gm)].at(-1);
35
+ if (!lastUseMatch) return {
36
+ code: `${getReferenceStr(await resolveFn(cssFile, code, id))}\n${code}`,
37
+ map: null
38
+ };
39
+ const before = code.substring(0, lastUseMatch.index);
40
+ const after = code.substring(lastUseMatch.index + lastUseMatch[0].length);
41
+ return {
42
+ code: `${before}${getReferenceStr(await resolveFn(cssFile, code, id))}\n${after}`,
43
+ map: null
44
+ };
45
+ }
46
+ };
47
+ };
48
+ //#endregion
49
+ export { tailwindAutoReference as default };
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "vite-plugin-tailwind-ref",
3
+ "version": "1.0.0",
4
+ "description": "A Vite plugin that automatically adds @reference directives to CSS files and framework style blocks (Svelte, Vue, etc.) using Tailwind CSS @apply",
5
+ "keywords": [
6
+ "vite",
7
+ "vite-plugin",
8
+ "tailwindcss",
9
+ "tailwind",
10
+ "css",
11
+ "svelte",
12
+ "vue",
13
+ "reference",
14
+ "apply"
15
+ ],
16
+ "homepage": "https://github.com/awaiden/vite-plugin-tailwind-ref#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/awaiden/vite-plugin-tailwind-ref/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/awaiden/vite-plugin-tailwind-ref.git"
23
+ },
24
+ "license": "MIT",
25
+ "author": "awaiden",
26
+ "type": "module",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.mts",
30
+ "import": "./dist/index.mjs"
31
+ }
32
+ },
33
+ "main": "./dist/index.mjs",
34
+ "types": "./dist/index.d.mts",
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "scripts": {
41
+ "build": "tsdown",
42
+ "format": "prettier --write .",
43
+ "lint": "eslint .",
44
+ "prepare": "husky",
45
+ "prepublishOnly": "bun run build"
46
+ },
47
+ "lint-staged": {
48
+ "*.{ts,js,mjs}": [
49
+ "eslint --fix",
50
+ "prettier --write"
51
+ ],
52
+ "*.{json,md}": [
53
+ "prettier --write"
54
+ ]
55
+ },
56
+ "dependencies": {},
57
+ "devDependencies": {
58
+ "@eslint/js": "^10.0.1",
59
+ "@types/node": "^25.9.1",
60
+ "eslint": "^10.4.0",
61
+ "eslint-plugin-perfectionist": "^5.9.0",
62
+ "husky": "^9.1.7",
63
+ "lint-staged": "^17.0.5",
64
+ "prettier": "^3.8.3",
65
+ "prettier-plugin-packagejson": "^3.0.2",
66
+ "tsdown": "^0.22.0",
67
+ "typescript": "^6.0.3",
68
+ "typescript-eslint": "^8.60.0",
69
+ "unrun": "^0.3.0"
70
+ },
71
+ "peerDependencies": {
72
+ "vite": "^8.0.14"
73
+ }
74
+ }