Last active
April 24, 2022 20:44
-
-
Save davepeck/3155eb3be480db05c4f4095150ff0fa5 to your computer and use it in GitHub Desktop.
Example of how to run vscode's built-in CSS validations from the command-line. Use `node validate-css.mjs *.css`.
This file contains 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
import fs from "fs"; | |
import url from "url"; | |
import { getCSSLanguageService } from "vscode-css-languageservice"; | |
import { TextDocument } from "vscode-languageserver-textdocument"; | |
/** Human-readable names for the potential diagnostic severities returned. */ | |
const severities = { 1: "ERR", 2: "WARN", 3: "INFO", 4: "HINT" }; | |
/** Format a position in a given file. */ | |
const formatPosition = (path, position) => | |
`${path}:${position.line + 1}:${position.character + 1}`; | |
/** Format a single diagnostic in a human-friendly fashion. */ | |
const formatDiagnostic = (diagnostic) => | |
`${formatPosition(diagnostic.path, diagnostic.range.start)} [${severities[diagnostic.severity]}] ${diagnostic.message} ${diagnostic.source}(${diagnostic.code})`; | |
const service = getCSSLanguageService(); | |
// Walk through all target files, generating diagnostics for each. | |
const diagnostics = process.argv.slice(2).flatMap(path => { | |
const lintUrl = url.pathToFileURL(path); | |
const lintText = fs.readFileSync(path, "utf8"); | |
const lintDocument = TextDocument.create(lintUrl.toString(), "css", 0, lintText); | |
const validation = service.doValidation(lintDocument, service.parseStylesheet(lintDocument)); | |
return validation.map(diagnostic => ({...diagnostic, path})); | |
}); | |
// Print out the diagnostics, if any. | |
if (diagnostics.length > 0) { | |
console.error(diagnostics.map(formatDiagnostic).join("\n")); | |
process.exit(1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You'll want to
npm install --save-dev vscode-css-languageservice
.