├── .eslintrc.json ├── .github ├── css-demo.gif └── jss-demo.gif ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── .vscodeignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── media └── icon.png ├── package-lock.json ├── package.json ├── src ├── constants.ts ├── extension.ts ├── lib │ └── WorkspaceFolderClient.ts ├── test │ ├── runTest.ts │ └── suite │ │ ├── extension.test.ts │ │ └── index.ts └── utils │ ├── config.ts │ ├── converter.ts │ ├── log.ts │ ├── object.ts │ └── selections.ts └── tsconfig.json /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "parserOptions": { 5 | "ecmaVersion": 6, 6 | "sourceType": "module" 7 | }, 8 | "plugins": [ 9 | "@typescript-eslint" 10 | ], 11 | "rules": { 12 | "@typescript-eslint/naming-convention": "warn", 13 | "@typescript-eslint/semi": "warn", 14 | "curly": "warn", 15 | "eqeqeq": "warn", 16 | "no-throw-literal": "warn", 17 | "semi": "off" 18 | }, 19 | "ignorePatterns": [ 20 | "out", 21 | "dist", 22 | "**/*.d.ts" 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /.github/css-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jackardios/vscode-css-to-tailwindcss/7eedcf899fc47e3402c55fc8f6a4cbc2b551ea6d/.github/css-demo.gif -------------------------------------------------------------------------------- /.github/jss-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jackardios/vscode-css-to-tailwindcss/7eedcf899fc47e3402c55fc8f6a4cbc2b551ea6d/.github/jss-demo.gif -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | dist 3 | node_modules 4 | .vscode-test/ 5 | *.vsix 6 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "dbaeumer.vscode-eslint", 6 | "esbenp.prettier-vscode", 7 | "connor4312.esbuild-problem-matchers" 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | // A launch configuration that compiles the extension and then opens it inside a new window 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | { 6 | "version": "0.2.0", 7 | "configurations": [ 8 | { 9 | "name": "Run Extension", 10 | "type": "extensionHost", 11 | "request": "launch", 12 | "args": [ 13 | "--extensionDevelopmentPath=${workspaceFolder}" 14 | ], 15 | "outFiles": [ 16 | "${workspaceFolder}/out/**/*.js" 17 | ], 18 | "preLaunchTask": "npm: watch" 19 | }, 20 | { 21 | "name": "Extension Tests", 22 | "type": "extensionHost", 23 | "request": "launch", 24 | "args": [ 25 | "--extensionDevelopmentPath=${workspaceFolder}", 26 | "--extensionTestsPath=${workspaceFolder}/out/test/suite/index" 27 | ], 28 | "outFiles": [ 29 | "${workspaceFolder}/out/test/**/*.js" 30 | ], 31 | "preLaunchTask": "${defaultBuildTask}" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "files.exclude": { 4 | "out": false // set this to true to hide the "out" folder with the compiled JS files 5 | }, 6 | "search.exclude": { 7 | "out": true // set this to false to include "out" folder in search results 8 | }, 9 | // Turn off tsc task auto detection since we have the necessary tasks as npm scripts 10 | "typescript.tsc.autoDetect": "off" 11 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | // See https://go.microsoft.com/fwlink/?LinkId=733558 2 | // for the documentation about the tasks.json format 3 | { 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "npm", 8 | "script": "watch", 9 | "group": "build", 10 | "problemMatcher": "$esbuild-watch", 11 | "isBackground": true, 12 | "label": "npm: watch" 13 | }, 14 | { 15 | "type": "npm", 16 | "script": "build", 17 | "group": "build", 18 | "problemMatcher": "$esbuild", 19 | "label": "npm: build" 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /.vscodeignore: -------------------------------------------------------------------------------- 1 | .vscode/** 2 | .vscode-test/** 3 | out/test/** 4 | src/** 5 | .gitignore 6 | .yarnrc 7 | vsc-extension-quickstart.md 8 | **/tsconfig.json 9 | **/.eslintrc.json 10 | **/*.map 11 | **/*.ts -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ### 1.2.6 4 | 5 | - Fix: flex property should convert considering the default values for flexShrink and flexBasis 6 | 7 | ### 1.2.5 8 | 9 | - Fix: temporary id is replaced with & only once 10 | 11 | ### 1.2.3 12 | 13 | - Fix missing declarations when converting CSSinJS 14 | 15 | ### 1.2.2 16 | 17 | - Fix fallback TailwindConverter 18 | 19 | ### 1.2.1 20 | 21 | - Fix incorrect conversion of border declaration 22 | 23 | ### 1.2.0 24 | 25 | - Update `css-to-tailwindcss` package to stable v1 26 | - Change extension namespace from `css-to-tailwindcss` to `cssToTailwindCss` 27 | - Add `cssToTailwindCss.arbitraryProperties` configuration 28 | 29 | ### 1.1.1 30 | 31 | - Fix: media expression is not converted if it has no screen parameters 32 | 33 | ### 1.1.0 34 | 35 | - Add CSS-in-JS support 36 | - Fix output CSS formatting 37 | 38 | ### 1.0.0 39 | 40 | - Initial release 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Salakhutdinov Salavat 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CSS to TailwindCSS converter (VS Code extension) 2 | 3 | **[🔗 NPM Package](https://github.com/Jackardios/css-to-tailwindcss/)** 4 | 5 | 🔄 Convert your **CSS** to **TailwindCSS** considering workspace tailwind configuration in a few clicks. 6 | 7 | ![VSCode extension demo](.github/css-demo.gif) 8 | 9 | You can even convert simple JS objects!: 10 | 11 | ![VSCode extension demo](.github/jss-demo.gif) 12 | 13 | ## Features: 14 | 15 | - supports all (or almost all) the features currently available in TailwindCSS 16 | - supports nested sass-like syntax 17 | - automatically finds tailwind config in your workspace and uses it for conversion (it is possible to configure config file path) 18 | - colors are matched regardless of the format used 19 | - rem is converted to px (it is possible to configure the rem size) 20 | - non-convertible CSS declarations are simply skipped 21 | - [ambiguities](https://tailwindcss.com/docs/adding-custom-styles#resolving-ambiguities) when using css variables are resolved automatically 22 | 23 | ## Installation 24 | 25 | **[Install via the Visual Studio Code Marketplace →](https://marketplace.visualstudio.com/items?itemName=Jackardios.vscode-css-to-tailwindcss)** 26 | 27 | The extension finds the first [Tailwind config file](https://tailwindcss.com/docs/installation#create-your-configuration-file) named `tailwind.config.js` or `tailwind.config.cjs` in your workspace and uses it when converting CSS. Use `tailwindCSS.experimental.configFile` setting to manually specify the config file(s) yourself instead. 28 | 29 | ## Usage 30 | 31 | 1. Select the CSS you want to convert to TailwindCSS 32 | 2. Open command pallete (Mac: Shift+Cmd+P; Windows: Shift+Ctrl+P) 33 | 3. Run "Convert CSS to TailwindCSS" command 34 | 35 | For more convenience, you can also assign a keyboard shortcut to the "Convert CSS to TailwindCSS" command. 36 | 37 | ## Extension Settings 38 | 39 | To avoid duplicate settings, this extension uses the [Tailwind CSS IntelliSense](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) settings 40 | 41 | ### `cssToTailwindCss.arbitraryProperties` 42 | 43 | **Default: `false`** 44 | 45 | Defines whether non-convertible properties should be converted as [arbitrary properties](https://tailwindcss.com/docs/adding-custom-styles#arbitrary-properties). 46 | 47 | ### `tailwindCSS.rootFontSize` 48 | 49 | **Default: `16`** 50 | 51 | Root font size in pixels. Used to convert `rem` CSS values to their `px` equivalents. 52 | 53 | ### `tailwindCSS.experimental.configFile` 54 | 55 | **Default: `null`** 56 | 57 | By default the extension will automatically use the first `tailwind.config.js` or `tailwind.config.cjs` file in your workspace that it can find to provide CSS to TailwindCSS converting. Use this setting to manually specify the config file(s) yourself instead. 58 | 59 | Example: 60 | 61 | ``` 62 | "tailwindCSS.experimental.configFile": ".config/tailwind.config.js" 63 | ``` 64 | 65 | ## Release Notes 66 | 67 | ### 1.2.6 68 | 69 | - Fix: flex property should convert considering the default values for flexShrink and flexBasis 70 | 71 | ### 1.2.5 72 | 73 | - Fix: temporary id is replaced with & only once 74 | 75 | ### 1.2.3 76 | 77 | - Fix missing declarations when converting CSSinJS 78 | 79 | ### 1.2.2 80 | 81 | - Fix fallback TailwindConverter 82 | 83 | ### 1.2.1 84 | 85 | - Fix incorrect conversion of border declaration 86 | 87 | ### 1.2.0 88 | 89 | - Update `css-to-tailwindcss` package to stable v1 90 | - Change extension namespace from `css-to-tailwindcss` to `cssToTailwindCss` 91 | - Add `cssToTailwindCss.arbitraryProperties` configuration 92 | 93 | ### 1.1.1 94 | 95 | - Fix: media expression is not converted if it has no screen parameters 96 | 97 | ### 1.1.0 98 | 99 | - Add CSS-in-JS support 100 | - Fix output CSS formatting 101 | 102 | ### 1.0.0 103 | 104 | - Initial release 105 | -------------------------------------------------------------------------------- /media/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jackardios/vscode-css-to-tailwindcss/7eedcf899fc47e3402c55fc8f6a4cbc2b551ea6d/media/icon.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vscode-css-to-tailwindcss", 3 | "displayName": "CSS to TailwindCSS converter", 4 | "description": "CSS to TailwindCSS 3.x converter extension for Visual Studio Code", 5 | "author": "Salavat Salakhutdinov ", 6 | "license": "MIT", 7 | "version": "1.2.6", 8 | "homepage": "https://github.com/jackardios/vscode-css-to-tailwindcss", 9 | "bugs": { 10 | "url": "https://github.com/jackardios/vscode-css-to-tailwindcss/issues", 11 | "email": "hello@bradley.dev" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/jackardios/vscode-css-to-tailwindcss.git" 16 | }, 17 | "publisher": "Jackardios", 18 | "keywords": [ 19 | "convert", 20 | "converter", 21 | "conversion", 22 | "css", 23 | "postcss", 24 | "tailwind", 25 | "tailwindcss", 26 | "css-to-tailwind", 27 | "vscode" 28 | ], 29 | "engines": { 30 | "vscode": "^1.74.0" 31 | }, 32 | "categories": [ 33 | "Other" 34 | ], 35 | "icon": "media/icon.png", 36 | "activationEvents": [ 37 | "onStartupFinished" 38 | ], 39 | "main": "./out/extension.js", 40 | "contributes": { 41 | "commands": [ 42 | { 43 | "command": "cssToTailwindCss.convertCssToTailwindCss", 44 | "title": "Convert CSS to TailwindCSS" 45 | } 46 | ], 47 | "configuration": { 48 | "title": "CSS to TailwindCSS converter", 49 | "properties": { 50 | "cssToTailwindCss.arbitraryProperties": { 51 | "type": "boolean", 52 | "default": false, 53 | "markdownDescription": "Defines whether non-convertible properties should be converted as 'arbitrary properties'." 54 | } 55 | } 56 | } 57 | }, 58 | "scripts": { 59 | "vscode:prepublish": "npm run esbuild-base -- --minify", 60 | "esbuild-base": "rimraf out && esbuild ./src/extension.ts --bundle --outfile=out/extension.js --external:vscode --format=cjs --platform=node", 61 | "build": "npm run esbuild-base -- --sourcemap", 62 | "watch": "npm run esbuild-base -- --sourcemap --watch", 63 | "test-compile": "tsc -p ./", 64 | "pretest": "npm run test-compile && npm run lint", 65 | "lint": "eslint src --ext ts", 66 | "test": "node ./out/test/runTest.js" 67 | }, 68 | "devDependencies": { 69 | "@types/glob": "^8.0.0", 70 | "@types/micromatch": "^4.0.2", 71 | "@types/mocha": "^10.0.1", 72 | "@types/node": "16.x", 73 | "@types/postcss-js": "^4.0.0", 74 | "@types/vscode": "^1.74.0", 75 | "@typescript-eslint/eslint-plugin": "^5.45.0", 76 | "@typescript-eslint/parser": "^5.45.0", 77 | "@vscode/test-electron": "^2.2.0", 78 | "esbuild": "^0.17.5", 79 | "eslint": "^8.28.0", 80 | "glob": "^8.0.3", 81 | "mocha": "^10.1.0", 82 | "rimraf": "^4.1.2", 83 | "typescript": "^4.9.3" 84 | }, 85 | "dependencies": { 86 | "css-to-tailwindcss": "^1.0.4", 87 | "micromatch": "^4.0.5", 88 | "nanoid": "^4.0.1", 89 | "postcss-js": "^4.0.0", 90 | "postcss-nested": "^6.0.0", 91 | "replace-string": "^4.0.0", 92 | "tolerant-json-parser": "^1.0.1" 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/constants.ts: -------------------------------------------------------------------------------- 1 | export const EXTENSION_NAME = "CSS To TailwindCSS converter"; 2 | export const CONFIG_FILE_GLOB = 3 | "{tailwind,tailwind.config,tailwind.*.config,tailwind.config.*}.{js,cjs,mjs}"; 4 | -------------------------------------------------------------------------------- /src/extension.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | import { TailwindConverter } from "css-to-tailwindcss"; 3 | 4 | import { 5 | DEFAULT_CONVERTER_CONFIG, 6 | WorkspaceFolderClient, 7 | } from "./lib/WorkspaceFolderClient"; 8 | import { replaceCurrentSelection } from "./utils/selections"; 9 | import { convertToTailwindCSS } from "./utils/converter"; 10 | 11 | let clients: Map = new Map(); 12 | 13 | function makeKeyByFolder(folder: vscode.WorkspaceFolder) { 14 | return folder.uri.toString(); 15 | } 16 | 17 | function getClientByFolder(folder: vscode.WorkspaceFolder) { 18 | return clients.get(makeKeyByFolder(folder)) || null; 19 | } 20 | 21 | function createClientByFolder( 22 | folder: vscode.WorkspaceFolder, 23 | context: vscode.ExtensionContext 24 | ) { 25 | const key = makeKeyByFolder(folder); 26 | const foundClient = clients.get(key); 27 | if (foundClient) { 28 | return foundClient; 29 | } 30 | 31 | const client = new WorkspaceFolderClient(folder, context); 32 | clients.set(key, client); 33 | client.init(); 34 | 35 | return client; 36 | } 37 | 38 | function deleteClientByFolder(folder: vscode.WorkspaceFolder) { 39 | const key = makeKeyByFolder(folder); 40 | clients.get(key)?.destroy(); 41 | clients.delete(key); 42 | } 43 | 44 | function getClientByActiveTextEditor(editor: vscode.TextEditor | undefined) { 45 | if (!editor) { 46 | return null; 47 | } 48 | 49 | const folder = vscode.workspace.getWorkspaceFolder(editor?.document.uri); 50 | 51 | if (!folder) { 52 | return null; 53 | } 54 | 55 | return getClientByFolder(folder); 56 | } 57 | 58 | export function activate(context: vscode.ExtensionContext) { 59 | vscode.workspace.workspaceFolders?.forEach((folder) => { 60 | createClientByFolder(folder, context); 61 | }); 62 | 63 | context.subscriptions.push( 64 | vscode.commands.registerCommand( 65 | "cssToTailwindCss.convertCssToTailwindCss", 66 | () => 67 | replaceCurrentSelection(async (selectionText) => { 68 | const converter = 69 | getClientByActiveTextEditor( 70 | vscode.window.activeTextEditor 71 | )?.getCurrentTailwindConverter() || 72 | new TailwindConverter(DEFAULT_CONVERTER_CONFIG); 73 | 74 | return await convertToTailwindCSS(selectionText, converter); 75 | }) 76 | ), 77 | 78 | vscode.workspace.onDidChangeConfiguration((event) => { 79 | clients.forEach((client, key) => { 80 | const folder = vscode.workspace.getWorkspaceFolder( 81 | vscode.Uri.parse(key) 82 | ); 83 | 84 | if ( 85 | event.affectsConfiguration("cssToTailwindCss", folder) || 86 | event.affectsConfiguration( 87 | "tailwindCSS.experimental.configFile", 88 | folder 89 | ) || 90 | event.affectsConfiguration("tailwindCSS.rootFontSize", folder) 91 | ) { 92 | client.refresh(); 93 | } 94 | }); 95 | }), 96 | 97 | vscode.workspace.onDidChangeWorkspaceFolders((event) => { 98 | for (let folder of event.added) { 99 | createClientByFolder(folder, context); 100 | } 101 | for (let folder of event.removed) { 102 | deleteClientByFolder(folder); 103 | } 104 | }) 105 | ); 106 | } 107 | 108 | export function deactivate() { 109 | clients.forEach((client) => client.destroy()); 110 | clients = new Map(); 111 | } 112 | -------------------------------------------------------------------------------- /src/lib/WorkspaceFolderClient.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | import { TailwindConverter, TailwindConverterConfig } from "css-to-tailwindcss"; 3 | 4 | import { CONFIG_FILE_GLOB } from "../constants"; 5 | import { Log } from "../utils/log"; 6 | import { loadConfigFile } from "../utils/config"; 7 | 8 | const DEFAULT_TAILWIND_CONFIG_FILE_PATTERN = `**/${CONFIG_FILE_GLOB}`; 9 | 10 | export const DEFAULT_CONVERTER_CONFIG: Partial = { 11 | postCSSPlugins: [require("postcss-nested")], 12 | }; 13 | 14 | export class WorkspaceFolderClient { 15 | protected workspaceFolder: vscode.WorkspaceFolder; 16 | protected extensionContext: vscode.ExtensionContext; 17 | protected converterConfig: Partial; 18 | protected tailwindConfigFilePattern: vscode.RelativePattern | null = null; 19 | protected currentConfigFileWatcher: vscode.FileSystemWatcher | null = null; 20 | protected currentConverter: TailwindConverter | null = null; 21 | 22 | constructor( 23 | workspaceFolder: vscode.WorkspaceFolder, 24 | extensionContext: vscode.ExtensionContext 25 | ) { 26 | this.workspaceFolder = workspaceFolder; 27 | this.extensionContext = extensionContext; 28 | this.converterConfig = DEFAULT_CONVERTER_CONFIG; 29 | } 30 | 31 | async init() { 32 | await this.refresh(); 33 | } 34 | 35 | async refresh() { 36 | await this.refreshSettings(); 37 | } 38 | 39 | async destroy() { 40 | this.stopConfigFileWatcher(); 41 | } 42 | 43 | getCurrentTailwindConverter() { 44 | return this.currentConverter; 45 | } 46 | 47 | protected async refreshSettings() { 48 | const converterSettings = vscode.workspace.getConfiguration( 49 | "cssToTailwindCss", 50 | this.workspaceFolder 51 | ); 52 | const intellisenseSettings = vscode.workspace.getConfiguration( 53 | "tailwindCSS", 54 | this.workspaceFolder 55 | ); 56 | 57 | let configFilePattern = intellisenseSettings.get( 58 | "experimental.configFile" 59 | ) as string | Record | undefined; 60 | 61 | let remInPx = parseInt(intellisenseSettings.get("rootFontSize") || "16"); 62 | 63 | if (configFilePattern && typeof configFilePattern !== "string") { 64 | Log.error( 65 | "Only 'string' is supported for `tailwindCSS.experimental.configFile` configuration so far" 66 | ); 67 | 68 | configFilePattern = DEFAULT_TAILWIND_CONFIG_FILE_PATTERN; 69 | } 70 | 71 | const oldTailwindConfigFilePattern = this.tailwindConfigFilePattern; 72 | this.tailwindConfigFilePattern = new vscode.RelativePattern( 73 | this.workspaceFolder.uri.fsPath, 74 | configFilePattern 75 | ? configFilePattern 76 | : DEFAULT_TAILWIND_CONFIG_FILE_PATTERN 77 | ); 78 | 79 | this.converterConfig.remInPx = isNaN(remInPx) ? 16 : remInPx; 80 | this.converterConfig.arbitraryPropertiesIsEnabled = !!converterSettings.get( 81 | "arbitraryProperties" 82 | ); 83 | 84 | if ( 85 | !this.patternsIsEqual( 86 | oldTailwindConfigFilePattern, 87 | this.tailwindConfigFilePattern 88 | ) 89 | ) { 90 | await this.refreshConfigFileWatcher(); 91 | } 92 | this.refreshConverter(); 93 | } 94 | 95 | protected async refreshConverter() { 96 | this.currentConverter = new TailwindConverter(this.converterConfig); 97 | } 98 | 99 | protected async refreshConfigFileWatcher() { 100 | this.stopConfigFileWatcher(); 101 | 102 | if (!this.tailwindConfigFilePattern) { 103 | return; 104 | } 105 | 106 | const [foundFile] = await vscode.workspace.findFiles( 107 | this.tailwindConfigFilePattern 108 | ); 109 | await this.setTailwindConfigFromFile(foundFile?.fsPath || null); 110 | 111 | this.currentConfigFileWatcher = vscode.workspace.createFileSystemWatcher( 112 | this.tailwindConfigFilePattern 113 | ); 114 | 115 | // This handles the case where the project didn't have config file 116 | // but was created after VS Code was initialized 117 | this.currentConfigFileWatcher.onDidCreate(async (uri) => { 118 | Log.info( 119 | `Found New TailwindCSS Config File, Reloading...\n(${uri.fsPath})` 120 | ); 121 | 122 | await this.setTailwindConfigFromFile(uri.fsPath); 123 | }); 124 | 125 | // Changes configuration should invalidate above cache 126 | this.currentConfigFileWatcher.onDidChange(async (uri) => { 127 | Log.info( 128 | `TailwindCSS Config File Changed, Reloading...\n(${uri.fsPath})` 129 | ); 130 | 131 | await this.setTailwindConfigFromFile(uri.fsPath); 132 | }); 133 | 134 | // If the config is deleted, utilities&variants should be regenerated 135 | this.currentConfigFileWatcher.onDidDelete(async (uri) => { 136 | Log.info( 137 | `TailwindCSS Config File Deleted, Reloading...\n(${uri.fsPath})` 138 | ); 139 | 140 | await this.setTailwindConfigFromFile(null); 141 | }); 142 | } 143 | 144 | protected stopConfigFileWatcher() { 145 | this.currentConfigFileWatcher?.dispose(); 146 | this.currentConfigFileWatcher = null; 147 | } 148 | 149 | protected patternsIsEqual( 150 | first: vscode.RelativePattern | null, 151 | second: vscode.RelativePattern | null 152 | ) { 153 | return ( 154 | first?.baseUri.fsPath === second?.baseUri.fsPath && 155 | first?.pattern === second?.pattern 156 | ); 157 | } 158 | 159 | protected async setTailwindConfigFromFile(filePath: string | null) { 160 | if (filePath) { 161 | try { 162 | this.converterConfig.tailwindConfig = await loadConfigFile(filePath); 163 | } catch (e) { 164 | Log.error(`Failed to read configuration\n(${filePath})`); 165 | } 166 | } else { 167 | delete this.converterConfig.tailwindConfig; 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/test/runTest.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | 3 | import { runTests } from '@vscode/test-electron'; 4 | 5 | async function main() { 6 | try { 7 | // The folder containing the Extension Manifest package.json 8 | // Passed to `--extensionDevelopmentPath` 9 | const extensionDevelopmentPath = path.resolve(__dirname, '../../'); 10 | 11 | // The path to test runner 12 | // Passed to --extensionTestsPath 13 | const extensionTestsPath = path.resolve(__dirname, './suite/index'); 14 | 15 | // Download VS Code, unzip it and run the integration test 16 | await runTests({ extensionDevelopmentPath, extensionTestsPath }); 17 | } catch (err) { 18 | console.error('Failed to run tests'); 19 | process.exit(1); 20 | } 21 | } 22 | 23 | main(); 24 | -------------------------------------------------------------------------------- /src/test/suite/extension.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from "assert"; 2 | 3 | import * as vscode from "vscode"; 4 | // import * as myExtension from '../../extension'; 5 | 6 | suite("Extension Test Suite", () => { 7 | vscode.window.showInformationMessage("Start all tests."); 8 | 9 | test("Sample test", () => { 10 | assert.strictEqual(-1, [1, 2, 3].indexOf(5)); 11 | assert.strictEqual(-1, [1, 2, 3].indexOf(0)); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /src/test/suite/index.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | import * as Mocha from 'mocha'; 3 | import * as glob from 'glob'; 4 | 5 | export function run(): Promise { 6 | // Create the mocha test 7 | const mocha = new Mocha({ 8 | ui: 'tdd', 9 | color: true 10 | }); 11 | 12 | const testsRoot = path.resolve(__dirname, '..'); 13 | 14 | return new Promise((c, e) => { 15 | glob('**/**.test.js', { cwd: testsRoot }, (err, files) => { 16 | if (err) { 17 | return e(err); 18 | } 19 | 20 | // Add files to the test suite 21 | files.forEach(f => mocha.addFile(path.resolve(testsRoot, f))); 22 | 23 | try { 24 | // Run the mocha test 25 | mocha.run(failures => { 26 | if (failures > 0) { 27 | e(new Error(`${failures} tests failed.`)); 28 | } else { 29 | c(); 30 | } 31 | }); 32 | } catch (err) { 33 | console.error(err); 34 | e(err); 35 | } 36 | }); 37 | }); 38 | } 39 | -------------------------------------------------------------------------------- /src/utils/config.ts: -------------------------------------------------------------------------------- 1 | import { promises as fs } from "fs"; 2 | 3 | function requireUncached(module: string) { 4 | delete require.cache[require.resolve(module)]; 5 | return require(module); 6 | } 7 | 8 | export async function loadConfigFile( 9 | filepath: string 10 | ): Promise { 11 | let content: string | undefined; 12 | 13 | async function read() { 14 | if (content === null) { 15 | content = await fs.readFile(filepath, "utf-8"); 16 | } 17 | 18 | return content; 19 | } 20 | 21 | try { 22 | return JSON.parse((await read()) || ""); 23 | } catch { 24 | return requireUncached(filepath); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/utils/converter.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | import type { Root } from "postcss"; 3 | import { parse } from "tolerant-json-parser"; 4 | import postcss from "postcss"; 5 | import * as postcssJs from "postcss-js"; 6 | import { Log } from "./log"; 7 | import { TailwindConverter } from "css-to-tailwindcss"; 8 | import { nanoid } from "nanoid"; 9 | import { isPlainObject } from "./object"; 10 | import replaceString from "replace-string"; 11 | 12 | function wrapCSS(id: string, css: string) { 13 | return `${id} { ${css} }`; 14 | } 15 | 16 | function deepUnwrapAtRule(id: string, atRuleValue: any) { 17 | if (!isPlainObject(atRuleValue)) { 18 | return atRuleValue; 19 | } 20 | 21 | Object.keys(atRuleValue).forEach((itemKey) => { 22 | const itemValue = atRuleValue[itemKey]; 23 | 24 | if (itemKey.startsWith("@")) { 25 | deepUnwrapAtRule(id, itemValue); 26 | } else if (isPlainObject(itemValue)) { 27 | delete atRuleValue[itemKey]; 28 | Object.assign(atRuleValue, itemValue); 29 | } 30 | }); 31 | 32 | return atRuleValue; 33 | } 34 | 35 | function unwrapJSS(id: string, jss: Record) { 36 | const result = jss[id]; 37 | 38 | delete jss[id]; 39 | Object.keys(jss).forEach((key) => { 40 | const jssItem = jss[key]; 41 | if (key.startsWith("@")) { 42 | result[key] = deepUnwrapAtRule(id, jssItem); 43 | } else { 44 | result[replaceString(key, id, "&")] = jssItem; 45 | } 46 | }); 47 | 48 | return result; 49 | } 50 | 51 | export async function convertToTailwindCSS( 52 | input: string, 53 | tailwindConverter: TailwindConverter 54 | ) { 55 | try { 56 | const id = nanoid(); 57 | const jsObject = parse(input); 58 | const parsed = await postcss().process(jsObject, { 59 | parser: postcssJs.parse, 60 | }); 61 | const converted = await tailwindConverter.convertCSS( 62 | wrapCSS(id, parsed.css) 63 | ); 64 | return JSON.stringify( 65 | unwrapJSS(id, postcssJs.objectify(converted.convertedRoot as Root)), 66 | null, 67 | vscode.window.activeTextEditor?.options.tabSize || 4 68 | ); 69 | } catch {} 70 | 71 | try { 72 | return (await tailwindConverter.convertCSS(input)).convertedRoot.toString(); 73 | } catch (e) { 74 | Log.error(e); 75 | 76 | return input; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/utils/log.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Code from windicss/windicss-intellisense 3 | * 4 | * @see https://github.com/windicss/windicss-intellisense/blob/main/src/utils/console.ts 5 | */ 6 | import { OutputChannel, window } from "vscode"; 7 | import { EXTENSION_NAME } from "../constants"; 8 | 9 | export class Log { 10 | private static _channel: OutputChannel; 11 | 12 | static get outputChannel(): OutputChannel { 13 | if (!this._channel) { 14 | this._channel = window.createOutputChannel(EXTENSION_NAME); 15 | } 16 | return this._channel; 17 | } 18 | 19 | static raw(...values: any[]) { 20 | this.outputChannel.appendLine(values.map((i) => i.toString()).join(" ")); 21 | } 22 | 23 | static info(message: string, intend = 0) { 24 | this.outputChannel.appendLine(`${"\t".repeat(intend)}${message}`); 25 | } 26 | 27 | static warning(message: string, prompt = false, intend = 0) { 28 | if (prompt) { 29 | window.showWarningMessage(message); 30 | } 31 | Log.info(`⚠ WARN: ${message}`, intend); 32 | } 33 | 34 | static async error( 35 | err: Error | string | any = {}, 36 | prompt = true, 37 | intend = 0 38 | ) { 39 | if (typeof err !== "string") { 40 | Log.info(`🐛 ERROR: ${err.name}: ${err.message}\n${err.stack}`, intend); 41 | } 42 | 43 | if (prompt) { 44 | const openOutputButton = "Error Log"; 45 | const message = 46 | typeof err === "string" 47 | ? err 48 | : `${EXTENSION_NAME} Error: ${err.toString()}`; 49 | 50 | const result = await window.showErrorMessage(message, openOutputButton); 51 | if (result === openOutputButton) { 52 | this.show(); 53 | } 54 | } 55 | } 56 | 57 | static show() { 58 | this._channel.show(); 59 | } 60 | 61 | static divider() { 62 | this.outputChannel.appendLine("\n――――――\n"); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/utils/object.ts: -------------------------------------------------------------------------------- 1 | export function isPlainObject(value: any) { 2 | return typeof value === "object" && !Array.isArray(value) && value !== null; 3 | } 4 | -------------------------------------------------------------------------------- /src/utils/selections.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from "vscode"; 2 | 3 | export async function replaceCurrentSelection( 4 | replacer: (selectedText: string) => string | Promise 5 | ) { 6 | const editor = vscode.window.activeTextEditor; 7 | 8 | if (!editor) { 9 | return; 10 | } 11 | 12 | const selections = editor.selections; 13 | 14 | if (selections.length === 0) { 15 | return; 16 | } 17 | 18 | let replacements: { selection: vscode.Selection; replacement: string }[] = []; 19 | 20 | for (let selection of selections) { 21 | const selectedText = editor.document.getText(selection); 22 | 23 | if (!selectedText) { 24 | continue; 25 | } 26 | 27 | replacements.push({ 28 | selection, 29 | replacement: await replacer(selectedText), 30 | }); 31 | } 32 | 33 | return await editor.edit(async (builder) => { 34 | replacements.forEach(({ selection, replacement }) => { 35 | builder.replace(selection, replacement); 36 | }); 37 | }); 38 | } 39 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "ES2020", 5 | "outDir": "out", 6 | "lib": [ 7 | "ES2020" 8 | ], 9 | "sourceMap": true, 10 | "rootDir": "src", 11 | "strict": true /* enable all strict type-checking options */ 12 | /* Additional Checks */ 13 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 14 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 15 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 16 | }, 17 | "exclude": ["node_modules", ".vscode-test"] 18 | } 19 | --------------------------------------------------------------------------------