Node.js API
The Stylelint module includes a lint() function that provides the Node.js API.
const result = await stylelint.lint(options);Options
Section titled “Options”In addition to the standard options, the Node API accepts:
abortSignal
Section titled “abortSignal”An AbortSignal to cancel the lint operation. When the signal is aborted, stylelint.lint() will reject with the signal’s reason.
This is useful for long-running consumers like language servers that need to cancel in-flight linting when a document changes.
const controller = new AbortController();
const resultPromise = stylelint.lint({ code: "a {}", config: myConfig, abortSignal: controller.signal});
// Cancel the lint if needed.controller.abort();config
Section titled “config”Stylelint does not bother looking for a configuration file (e.g. stylelint.config.js) if you use this option.
A string to lint.
The directory from which Stylelint will look for files. Defaults to the current working directory returned by process.cwd().
A file glob, or array of file globs.
Relative globs are considered relative to cwd.
Though both files and code are “optional”, you must have one and cannot have both.
globbyOptions
Section titled “globbyOptions”The options used to match files. Stylelint supports a subset of globby’s options:
braceExpansion: expand braces, e.g.{a,b}. Defaults totrue.caseSensitiveMatch: match case-sensitively. Defaults totrue.dot: match files and directories whose names begin with a dot. Defaults tofalse.extglob: support extglobs, e.g.+(a|b). Defaults totrue.followSymbolicLinks: traverse symbolic links to directories. Defaults totrue.ignore: a glob, or array of globs, of files to exclude. Relative globs are considered relative tocwd.
Stylelint throws a configuration error for any other option.
The returned promise
Section titled “The returned promise”stylelint.lint() returns a Promise that resolves with an object containing the following properties:
A string that contains the autofixed code, if the fix option is set to true and the code option is provided. Otherwise, it is undefined.
The directory used as the working directory for the linting operation.
errored
Section titled “errored”Boolean. If true, at least one rule with an “error”-level severity registered a problem.
output
Section titled “output”postcssResults
Section titled “postcssResults”An array containing all the accumulated PostCSS LazyResults.
report
Section titled “report”A string that contains the formatted problems (using the default formatter or whichever you passed).
results
Section titled “results”An array containing all the Stylelint result objects (the objects that formatters consume).
maxWarningsExceeded
Section titled “maxWarningsExceeded”An object containing the maximum number of warnings and the amount found, e.g. { maxWarnings: 0, foundWarnings: 12 }.
The value of the color option, if it was set.
Result object
Section titled “Result object”{ "source": "path/to/file.css", // The filepath or PostCSS identifier like <input css 1> "errored": true, // This is `true` if at least one rule with an "error"-level severity triggered a warning "warnings": [ // Array of rule problem warning objects, each like the following ... { "line": 3, "column": 12, "endLine": 4, "endColumn": 15, "rule": "block-no-empty", "severity": "error", "text": "You should not have an empty block (block-no-empty)" } ], "deprecations": [ // Array of deprecation warning objects, each like the following ... { "text": "Feature X has been deprecated and will be removed in the next major version.", "reference": "https://stylelint.io/docs/feature-x.md" } ], "invalidOptionWarnings": [ // Array of invalid option warning objects, each like the following ... { "text": "Invalid option X for rule Y" } ], "ignored": true, // This is `true` if the file's path matches a provided ignore pattern "autofixed": true // This is `true` if the `fix` option changed the source}Edit info
Section titled “Edit info”When the computeEditInfo option is enabled, a warning may include a fix property that provides information about suggested fixes:
range([number, number]) - the pair of 0-based indices in source code text to removetext(string) - the text to add
For example, to change a { opacity: 10%; } to a { opacity: 0.1; }, the EditInfo might look like:
{ // "line", "column", "rule", ... "fix": { "range": [13, 16], // Indices of "10%" "text": "0.1" // Replacement text }}To apply this edit, you would:
const sourceCodeText = "a { opacity: 10%; }";const result = sourceCodeText.slice(0, edit.range[0]) + // "a { opacity: " edit.text + // "0.1" sourceCodeText.slice(edit.range[1]); // "; }"//=> "a { opacity: 0.1; }"Only a single EditInfo will be recorded for a specific region in source code. If multiple report ranges overlap, only the first will contain EditInfo.
Syntax errors
Section titled “Syntax errors”stylelint.lint() does not reject the Promise when your CSS contains syntax errors.
It resolves with an object (see the returned promise) that contains information about the syntax error.
Usage examples
Section titled “Usage examples”Example A
Section titled “Example A”As config contains no relative paths for extends or plugins, you do not have to use configBasedir:
try { const result = await stylelint.lint({ config: { rules: "color-no-invalid-hex" }, files: "all/my/stylesheets/*.css" }); // do things with result.report, result.errored, and result.results} catch (err) { // do things with err e.g. console.error(err.stack);}Example B
Section titled “Example B”If myConfig does contain relative paths for extends or plugins, you do have to use configBasedir:
const result = await stylelint.lint({ config: myConfig, configBasedir: url.fileURLToPath(new URL("configs", import.meta.url)), files: "all/my/stylesheets/*.css"});Example C
Section titled “Example C”Using a string code instead of a file glob, and the verbose formatter instead of the default JSON:
const result = await stylelint.lint({ code: "a { color: pink; }", config: myConfig, formatter: "verbose"});
// do things with result.reportThe report will be available as the value of the report property in the returned object.
Example D
Section titled “Example D”Using your own custom formatter function:
const result = await stylelint.lint({ config: myConfig, files: "all/my/stylesheets/*.css", formatter: (results) => { /* .. */ }});Example E
Section titled “Example E”Using a custom syntax:
const result = await stylelint.lint({ config: myConfig, files: "all/my/stylesheets/*.css", customSyntax: { parse(css, opts) { /* .. */ }, stringify(node, builder) { /* .. */ } }});Example F
Section titled “Example F”Using a string code and the fix option:
const result = await stylelint.lint({ code: "a { color: pink; }", config: { rules: { "hue-degree-notation": "angle" } }, fix: true});
// do things with result.codeThe autofixed code will be available as the value of the code property in the returned object.
Resolving the effective config for a file
Section titled “Resolving the effective config for a file”If you want to find out what exact configuration will be used for a file without actually linting it, you can use the resolveConfig() function. Given a file path, it will return a Promise that resolves with the effective configuration object:
const config = await stylelint.resolveConfig(filePath);
// config => {// rules: {// 'color-no-invalid-hex': true// },// extends: [// 'stylelint-config-standard',// 'stylelint-config-css-modules'// ],// plugins: [// 'stylelint-scss'// ],// …// }If a configuration cannot be found for a file, resolveConfig() will return a Promise that resolves to undefined.
You can also pass the following subset of the options that you would normally pass to lint():
cwdconfigconfigBasedircustomSyntax