Created
May 21, 2024 04:39
-
-
Save mdynnl/54d54d1be48cda8b8d003bc793453aa1 to your computer and use it in GitHub Desktop.
A workaround to support for classes inside css files in TailwindCSS Intellisense
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const path = require("path"); | |
| const fs = require("fs"); | |
| const stack = new Error().stack; | |
| const isExtension = process.title.includes("Code Helper (Plugin)") || stack.includes("dist/server.js"); | |
| /** | |
| * @param {import("tailwindcss/types/config").PluginAPI} api | |
| */ | |
| module.exports = function handler(api) { | |
| if (!isExtension) return; | |
| const paths = [api.config("layers", "index.css")].flat(); | |
| console.log("[class-intellisense] plugin loaded", paths); | |
| paths.flatMap(parseLayers).forEach((layer) => { | |
| layer.base && api.addBase(layer.base); | |
| layer.components && api.addComponents(layer.components); | |
| layer.utilities && api.addUtilities(layer.utilities); | |
| }); | |
| }; | |
| function parseLayers(filepath) { | |
| const resolved = path.resolve(__dirname, filepath); | |
| const basedir = path.dirname(resolved); | |
| if (!fs.existsSync(resolved)) return; | |
| const css = fs.readFileSync(resolved, "utf-8"); | |
| const parsed = require("postcss").parse(css); | |
| const currentLayers = {}; | |
| parsed.walkAtRules("layer", (layer) => { | |
| currentLayers[layer.params] ??= {}; | |
| layer.walkRules((rule) => { | |
| currentLayers[layer.params][rule.selector] = rule.nodes.reduce((o, n) => { | |
| switch (n.type) { | |
| case "atrule": | |
| if (n.name === "apply") { | |
| o[`@apply ${n.params}`] = ""; | |
| } | |
| break; | |
| case "decl": | |
| o[n.prop] = n.value; | |
| break; | |
| } | |
| return o; | |
| }, {}); | |
| }); | |
| }); | |
| const layers = [currentLayers]; | |
| parsed.walkAtRules("import", (imported) => { | |
| const [importee] = imported.params.split(" "); | |
| const url = /url\((.*?)\)/.exec(importee); | |
| const name = url ? url[1] : importee; | |
| const quoted = /['"](.*?)['"]/.exec(name); | |
| const unquoted = quoted ? quoted[1] : name; | |
| const absolutePath = path.resolve(basedir, unquoted); | |
| const layer = parseLayers(absolutePath); | |
| layer && layers.push(...layer); | |
| }); | |
| return layers; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment