Skip to content

HTML CLI

A CLI tool designed primarily for AI agents and automation scripts.
Provides the core logic for SpiraCSS HTML parsing and SCSS generation.

  • Primary use: AI agents (Codex, Claude Code, etc.) call this CLI to generate SCSS from HTML
  • Secondary use: The VS Code extension uses this package internally as its engine

This tool is not designed for direct human use from the terminal.
For manual SCSS generation, use the VS Code extension instead.

Install

Version 0.6.0 requires Node.js >=24.22.3 <25. Version 0.5.1 requires Node.js >=24.22.2 <25. Version 0.5.0 requires Node.js >=24.15.0 <25.

Version 0.6.0 adds the source-aware engine described below. These APIs and diagnostics are not available in 0.5.1.

Terminal window
yarn add -D @spiracss/html-cli
Terminal window
npm install -D @spiracss/html-cli

Commands

Command Description
spiracss-html-to-scss Generate SCSS from HTML
spiracss-html-lint Validate HTML structure against SpiraCSS rules
spiracss-html-format Insert placeholder classes (defaults: block-box / element)

spiracss-html-to-scss

Generates SCSS files from HTML files or templates. Runs structure linting by default and exits on errors (use --ignore-structure-errors to continue).

Basic usage

Terminal window
# Root mode (generate from the root element)
yarn spiracss-html-to-scss --root path/to/file.html
# Selection mode (treat input as a fragment)
yarn spiracss-html-to-scss --selection path/to/fragment.html
# From stdin
cat file.html | yarn spiracss-html-to-scss --selection --stdin --base-dir src/components/sample

Options

Option Description
--root Generate from the root element (treated as the root Block; default)
--selection Treat input as a fragment (selection mode)
--stdin Read HTML from stdin
--format FORMAT In 0.6.0, explicitly select html, webc, jsx, tsx, astro, or vue. Without this option, stdin defaults to html and files use extension inference.
--base-dir PATH Output directory for SCSS (overrides the input file directory; when using --stdin, defaults to the current directory)
--dry-run Print output paths only (no files written)
--json Output results as JSON to stdout (no files written; for AI/scripts)
--ignore-structure-errors Continue even if structure linting errors occur
--allow-provisional Continue with fallback defaults when spiracss.config.js is missing

Note:

  • --root and --selection are mutually exclusive. Omit both to use root mode; --root is retained as an explicit compatibility flag
  • In --root mode, a single element from the input is treated as the root, and SCSS is generated for the root and its descendants. If that element has no class, generation fails. Use this mode for component-level input
  • In --selection mode, if no elements have a class attribute, the CLI exits with an error
  • Even with --ignore-structure-errors, generation still fails when required preconditions are not met (no root element, multiple roots in root mode, or missing class on the root); when it continues, the process still exits non-zero so ignored errors are not reported as a normal pass
  • If spiracss.config.js is missing, the CLI blocks by default. --allow-provisional permits continuation but returns status: "provisional", ok: false, and exit code 1 in JSON output
  • JSON validation uses status: "pass" | "provisional" | "ignored" | "failed" | "blocked"; only pass has ok: true
  • Error message text can change; do not depend on exact strings

Output example

your-component/
├─ hero-section.scss -> root Block
├─ scss/
│ ├─ feature-card.scss -> child Block
│ └─ index.scss -> @use merged automatically
└─ your-template.html

Output rules

  • Output goes to the same directory as the input file when a path is specified (--base-dir overrides)
  • --stdin: --base-dir (defaults to the current directory)
  • Child Blocks go under childScssDir (default: scss)

SCSS root syntax (v0.5.0+)

generator.scssRootStyle is shared with the VS Code extension. The default is scope-explicit (@scope with a :scope body); scope selects direct contents, and class selects the previous root syntax. Versions before v0.5.0 do not support this setting.

Only the root-mode component root follows this setting. Child Block files loaded with meta.load-css() and selection-mode output retain class selectors. A component root without independent children still follows the setting; it simply omits the unnecessary meta include. Existing files and HTML classes are not migrated automatically.

generator: {
scssRootStyle: 'scope-explicit'
}

The conversion example below shows the v0.5.0 default root syntax. Its child files stay in class form. When Stylelint is configured through createRules(), scope settings require scope on component roots and accept either root body syntax. Every @scope in configured child Block directories is a lint error for all settings. See scope configuration.

Keep loaded children in class form. Sass prepends the loading parent’s selector inside a style rule; a child’s :scope loaded inside the default parent’s :scope becomes the non-matching :scope :scope. Do not move the root include as a repair because it changes child specificity. Migrate existing child scopes manually following the diagnostic.

Generation notes

  • When multiple elements share the same base class, modifier / variant / state / ARIA attributes are deduplicated and merged
  • Reserved keys can be changed via selectorPolicy (e.g. data-theme, data-status, aria-hidden, aria-expanded)
  • In data mode, variants are emitted in the base structure (you may manually move initial interaction values to the interaction section)

spiracss-html-lint

Validates HTML structure against SpiraCSS Block / Element / Modifier rules.

Missing configuration blocks validation by default. Use --allow-provisional only when fallback defaults are explicitly accepted; the result remains non-pass (status: "provisional", ok: false, exit code 1).

Basic usage

Terminal window
# Validate as a root element
yarn spiracss-html-lint --root path/to/file.html
# Validate a fragment from stdin
cat fragment.html | yarn spiracss-html-lint --selection --stdin
# Output JSON
yarn spiracss-html-lint --root path/to/file.html --json

Options

Option Description
--root Treat the root as a single Block (default)
--selection Treat input as multiple fragments
--stdin Read HTML from stdin
--json Output as JSON: { file, mode, ok, errors[] }

Source-aware engine (0.6.0)

Lint and generation select .html/.htm, .webc, .jsx, .tsx, .astro and .vue by extension. --format overrides the extension; stdin without it remains HTML. Unknown extensions are blocked (FORMAT_UNSUPPORTED), not silently interpreted as HTML. Explicit legacy .ejs, .njk, .nunjucks and .svelte inputs retain the bounded extraction path, identified as parserPath: "legacy"; this is not formal Svelte or template-language support. Formal-parser failures never fall back to legacy extraction.

The validation unit is the HTML/WebC source fragment, Astro template (excluding frontmatter/script/style), Vue SFC template or snippet, or a proven JSX/TSX returned expression. Separate component returns are separate units; arbitrary callback returns and auxiliary JSX variables are not automatically component roots. A same-scope single const inserted directly once as children can be linked to its visible parent. Other uncertain relationships remain localized unresolved evidence rather than invented ancestry.

JSX className is a scalar; a raw array/object is not Vue/Astro class-list syntax. Vue combines class and :class; Astro combines class and class:list. Recognized unshadowed imports from clsx/classnames allow bounded argument evaluation, not arbitrary JavaScript or a guessed cn wrapper. Literal strings, static templates, ternaries and &&/|| are evaluated finitely with branch conditions preserved. In-scope unknowns do not become pass. WebC’s relevant : attribute expressions use the confirmed serializer semantics; expressions without a reliable source mapping remain unresolved.

coverage.scope is "source": props forwarding, slot expansion and rendered DOM are out of scope, counted but not claimed as inspected. Existing HTML class names, ownership rules and leaf Blocks are unchanged. HTML has no design-level maximum Block nesting depth. MAX_DEPTH_EXCEEDED is the implementation safety guard (256).

Vue counts each source component element with unresolved class forwarding once, regardless of its number of bindings or v-else branches. Native elements do not add to that count; static-only components contribute zero. JSX counts unknown spreads separately, so counts are not comparable across formats. Proven visible-source violations remain reported even at counted sites. ESLint does not expose coverage.

JSON retains file, mode, ok, errors, configuration and five statuses (pass, provisional, ignored, failed, blocked). Only pass means exit 0 and ok: true. Parsed results add format, parserPath, coverage and metrics. Markup parses, expression parses and script parses are counted separately. Standalone Astro uses official synchronous convertToTSX, Babel and the official source map; astroConversions: 1 and generatedParses: 1 record both operations. Scope-local unresolved values are failed. Syntax (PARSE_ERROR), parser resource/internal failures (PARSER_RUNTIME_ERROR), invalid configuration (CONFIG_INVALID), unavailable config/parser and the depth guard are blocked. Resource failure is not evidence of invalid Astro syntax and must not trigger a class rename. Metadata may be absent before parsing can begin.

Each source diagnostic adds:

  • kind and reason; original UTF-16 half-open range: [start, end] and position only when attributable to the source;
  • repair.conditions and the relevant repair.effective settings, such as naming, customPatterns, external, selectorPolicy or mode; the object can be empty;
  • condition when a violation is proved only on that branch, and repair.missingInformation when a unique safe correction needs more information;
  • docs as a supplementary focused link.

Use code, target range and repair conditions as machine contracts, not exact message wording. UNCLASSIFIED_CLASS_TOKEN points to the later unclassified token. SOURCE_RELATION_UNRESOLVED identifies relevant evidence that is not settled. Previously merged siblings are now checked per occurrence, so existing input can produce more diagnostics and default generation can stop on newly detected errors. Generation alone still merges repeated structures; allowed-input filenames/order/content and format behavior are preserved.

MULTIPLE_ROOT_ELEMENTS means root mode expects one component root. Its repair.effective is { mode: "root" }, and repair.missingInformation asks which root is intended or whether selection mode is appropriate. Keep one intended root, or use selection mode for intentional multiple-component input; valid class names do not need renaming or removal.

In HTML and WebC, repeating class or a configured selectorPolicy attribute on one opening tag produces SOURCE_RELATION_UNRESOLVED and a failed result. Confirm the intended attribute in the original markup and rerun lint. This diagnostic does not select a winner, justify renaming valid classes or check every attribute for duplicates.

File-level parser/runtime/config/unsupported failures without original-location evidence omit both range and position, rather than inventing [0, 0] or 1:1. JSON consumers must accept their absence. A failure known only at a point uses range: [n, n], not an invented one-character span; a parser-provided end is retained. Proven source offset zero and EOF positions remain valid. ESLint may use a host-required file-start display location for a positionless report, not as source evidence. Depth/unsupported diagnostics have dedicated repair guidance, not naming instructions.

For Vue, the CLI uses the compiler’s original template locations and the ESLint integration uses the host parser’s ranges. They are tested to match for the supported static class forms. Entity-encoded binding expressions, script or expression syntax errors, and parser recovery can produce different diagnostics or locations in the two backends; this is not complete Vue grammar or diagnostic parity.

Normal Astro conversion reports astroConversions: 1, generatedParses: 1, scriptParses: 0. On generated-parse failure, the original frontmatter may be checked under both TypeScript and TSX grammars; public metrics retain the actual number of additional parses. A generated-only failure with no proven source cause stays blocked as PARSER_RUNTIME_ERROR, with cause-unknown guidance rather than an instruction to edit frontmatter or restore resources. Generated coordinates are not passed off as original source coordinates.

AI repair-loop acceptance

  1. Read the diagnostic range, reason, repair.effective, repair.conditions and any repair.missingInformation; no full-guide reload is necessary.
  2. Make the smallest change justified by those conditions. If component role or dynamic intent is missing, ask for that intent or supply static evidence; do not delete or rename behavior merely to get zero errors.
  3. Rerun the same format, mode and project configuration. Accept only pass; unsupported/unresolved is not a completed repair.

The repair loop does not promise automatic structural decisions or universal autofix.

Programmatic API and ESLint

const config = await loadProjectOptions(projectRoot)
if (config.configStatus !== 'loaded') throw new Error('Load the project config first')
const parsers = await loadMarkupParsers(['tsx'])
const result = lintMarkup(source, { format: 'tsx', mode: 'root', parsers, config })

Import these functions from @spiracss/html-cli. Parser handles and config are invocation-local; lintMarkup is synchronous after loading. Existing sync public APIs retain their signatures.

The optional @spiracss/html-cli/eslint subpath exports plugin (one markup rule, recommended error) and createMarkupEslintConfig(config, htmlParser). Pass preloaded resolved config. For HTML/WebC, supply @html-eslint/parser to that helper in flat config. Other format host parsers supply their ASTs directly with an explicit file match and rule options. The same validator and repair conditions are used; ESLint parser-fatal errors retain the host’s own syntax code/location rather than pretending to be rule diagnostics.

The rule does not reparse supplied markup or expression ASTs. For WebC, the thin HTML-parser wrapper performs the first parse of relevant dynamic attribute expressions and supplies them through parser services. Bypassing the wrapper does not make missing expression evidence static. No custom ESLint Language or arbitrary JavaScript evaluator is provided. Ordinary CLI use does not require installing ESLint.

When ESLint caching and RegExp custom naming patterns are used together, use createMarkupEslintConfig(config, parser, files) with the appropriate host parser and file matches. Its rule options serialize each pattern’s source and flags so changing either invalidates that cache identity. This is not a digest of arbitrary configuration or external state.

Recovery and alternative boundaries

After a guaranteed effective non-external Block/Element base, only known optional tokens whose presence cannot affect lint, generation or ownership are removed before forming class alternatives. Modifier/general ternary ordering, first-match diagnostic positions and branch guards are preserved; unknown spreads and owner-changing cases stay on the bounded existing path. classExpressionProducts counts attempted expression-alternative pairs and inertOptionalTokens counts static tokens removed before multiplication. This is not a solver or a budget increase; reserved-attribute alternatives retain their separate safety budget.

The official Astro conversion accepts some omitted closing tags (li, p, td) without preserving a trustworthy source tree. Proven local omission gets SOURCE_RELATION_UNRESOLVED with explicit-close guidance. When generated parsing succeeds but a boundary/attribute/child relation cannot be verified, guidance instead asks users to check that range’s expressions, comments and opening/closing correspondence: it does not claim parse/resource failure, prescribe naming changes or ask for an existing close to be added again. A local report uses a verified opening range; otherwise the failure stays cause-unknown and blocked without a fabricated position. Independently verified siblings remain checked; uncertain regions remain uninspected, without definite ownership/root-count claims, and document generation is unavailable. A genuinely missing backend/source map remains a runtime failure. Actual syntax errors use justified original token/frontmatter ranges; host parser syntax rejection before the rule is distinct.

Astro closing boundaries require verified original-source correspondence. Metadata/script-only roots retain “No source element found.” Native HTML close names alone are ASCII case-insensitive. The existing Astro ESLint parser still rejects </DIV> before the rule even when standalone accepts it; component names and unproved foreign namespaces are not folded.

Class composition is host-specific and precedes prefix-based optional-extra pruning. Vue retains attribute order: a later static class cannot lend a base to an earlier dynamic list. Astro places a direct ordinary class before its direct class:list at the list’s position. On native elements, spread-class and direct-list emissions are separate HTML class attributes and the first actually emitted one wins. Components use last same-name prop values after compiler folding, then normalize class before class:list: a later class spread does not erase the original class already folded into the separate list key. These cases are not interchangeable.

Native Astro resolves only inspected class/selector keys and relevant input type against actual output. Static className remains literal className (HTML-canonical classname); dynamic/shorthand/template/spread className uses the class alias. This Astro alias selection precedes ASCII-canonicalization of emitted native HTML names and does not describe component props, JSX or Vue key handling. Nullish attribute values are non-output; empty/whitespace ordinary class emits, and ordinary false emits the string false. class:list emits only a nonempty clsx result ([]/false do not emit; a whitespace string does). Known object spreads apply same-key overwrite while retaining JS key insertion order. Lint and SCSS use the same selected selector alternatives; unsupported scalar arrays stay unresolved.

For both lint and generation, JSX/TSX and Astro component spreads of null or proven unbound undefined contribute nothing, just like an omitted spread. Native Astro treats only proven unbound undefined this way. Native Astro null, shadowed undefined and other unknown spreads remain unknown.

Hidden input type is needed only on relevant classless branches. Known JSX props are last-wins, native Astro uses first emission, and Vue same-props-group duplicates are first-wins, separately from argumentless v-bind/mergeProps. Proven hidden is ASCII case-insensitive. Unknown type reports local SOURCE_RELATION_UNRESOLVED asking for static type evidence or intended hidden/non-hidden meaning, not a class addition or naming fix. Valid class/disabled classless checks add no unrelated type diagnostic. Proven unbound undefined is absent as a value and false as a predicate; bound or unproven cases remain unknown. classExpressionProducts includes outer joins and guard-incompatible attempted pairs; budgets are unchanged.

For existing inspected keys, presence, value and repair provenance are separate branch facts. Prohibitions use the actual producing attribute; value violations use its value. Nullable unknown alone proves no forbidden presence. Certain prohibited presence without a unique winner invents no repair range. Unknown value-named variant/state data values remain unresolved. Configured dynamic ARIA such as open or String(open) is lint-valid in default data mode if there are no other violations. No ARIA value naming or forced boolean-string rewrite is needed; rewriting can change nullable absence. Wholly unknown props forwarding, relevant input-type uncertainty and explicit ignore/direct-helper contracts retain their existing scope.

Generation emits reachable known winners only. Astro <div class="card-list" {...{"aria-expanded":open}} aria-expanded="true" aria-expanded="never"/> passes lint, generates only the known true selector, and reports coverage.generationUnenumeratedSites: 1. This counts applicable generation element/configured-key sites whose reachable values cannot be fully enumerated, once per site rather than branch/file. Absent, nonapplicable and definitely defeated unknowns do not count. The field is separate from errors, unresolved coverage, status and exit code. JSON reuses coverage; generation CLI and VS Code Output show one informational line only when nonzero. ESLint emits no generation-only diagnostic. Existing synchronous GeneratedFile[] APIs are unchanged and do not carry the count; callers use existing preflight lint coverage without reparsing solely for the note.

Dynamic configured data values remain unresolved, so results can differ from 0.5.1. Establish known valid values or supported finite alternatives only when intent is preserved; unknown runtime values are neither assumed valid nor blindly renamed.

Vue uses first-key order within one scalar props group and last-group order across argumentless v-bind/mergeProps for configured selector keys and relevant input type. Lint and SCSS consume the same winner, including legal values; losing selectors are not generated. Class/style/event merge is unchanged. Supported simple list objects preserve first key insertion and last value for both tokens and emission. A guarded falsy x && value contributes nothing to class:list. Directive recognition uses the original exact class:list key, not a later HTML-canonicalized CLASS:LIST spelling.

On Vue native elements in the HTML namespace, attributes, static bind arguments and literal object keys in argumentless v-bind use ASCII case-insensitive comparison for inspected scalar keys. Components and foreign namespaces such as SVG retain their written spelling. Class lists require the compiled key to be exactly class. Native Class, :Class, :class.prop, .class and :class.attr stay unresolved at the attribute range with DYNAMIC_CLASS_UNRESOLVED, without classless or root cascades. This conservatively includes a static Class="card-list". The generic reason need not identify the spelling or target; this is not general scalar .prop, .attr or .camel support.

When two differently spelled Vue attributes map to the same configured scalar key, the later whole attribute is unresolved, without a claimed winner. Identically spelled duplicates remain compiler PARSE_ERROR in both entry points. This collision guarantee covers two attributes only. Collisions involving three or more sources, including object literals in argumentless v-bind, are unsupported.

Shorthand Astro fragments require verified original delimiters and source relationships. Unverified regions localize to a verified enclosing opening where possible; otherwise they remain positionless and blocked. Independently verified siblings remain checked, but uncertain document generation is unavailable.

A document with a doctype and raw text before a top-level shorthand Fragment is a known unsupported Astro form. Standalone reports positionless PARSER_RUNTIME_ERROR and is blocked; the ESLint host emits no SpiraCSS diagnostic for that input. Host silence is not a universal pass or evidence that standalone accepts the document.

When a supplied HTML/WebC AST absorbs actual following elements into RAWTEXT/RCDATA beyond a real source closing tag, the rule reports local SOURCE_RELATION_UNRESOLVED and recommends the native CLI. It neither asks users to change valid text, naming or nesting nor reparses/reattaches lost elements. Legitimate opaque text through EOF remains accepted. This constraint is separate from malformed-source recovery.

HTML recovery reports unresolved evidence for select loss, table foster parenting and non-void self-closing. Duplicate relevant attributes are reported separately as described above. If recovery retains a known static class without a precise value span, its diagnostic may use the original attribute range rather than a token range; recovery evidence remains unresolved. For some unclosed attribute quotes (eof-in-tag), standalone reports unresolved evidence while the current supplied HTML host may not report the same recovery evidence. This known malformed-input difference is not general HTML-validity support. Close the original quote and rerun the same host; these reports do not provide an independent recovery parser.

Astro wide-input verification boundary

With astro-eslint-parser 3.2.0, @astrojs/compiler-rs 0.5.3 and ESLint 10.14.0, a 70,000-element Astro input did not finish within 45 seconds even with the SpiraCSS rule disabled. This time is spent in the host rather than the rule; it does not establish a particular upstream bug.

Standalone completion does not establish large-input host support or a performance guarantee. There is no size cap or legacy fallback. Before relying on larger host inputs, confirm this limitation is acceptable and verify those inputs in your environment.

Note:

  • In --root mode, a single element from the input is treated as the root and the root plus its descendants are validated
  • If the root element has no class, INVALID_BASE_CLASS is reported
  • Use this mode for component-level input. If you have multiple root Blocks, use --selection
  • --root and --selection are mutually exclusive. Omit both to use root mode; --root is retained as an explicit compatibility flag

Error codes

Code Description
INVALID_BASE_CLASS Base class violates Block/Element naming rules, or the root has no class, or no eligible elements were found
MODIFIER_WITHOUT_BASE Modifier class without a base class
DISALLOWED_MODIFIER Modifier class used in data mode (both variant/state are data)
UTILITY_WITHOUT_BASE Utility class without a base class
MULTIPLE_BASE_CLASSES Multiple base classes found
ROOT_NOT_BLOCK Root element is not a Block
ELEMENT_WITHOUT_BLOCK_ANCESTOR Element has no Block ancestor
ELEMENT_PARENT_OF_BLOCK Element is the parent of a Block
DISALLOWED_VARIANT_ATTRIBUTE Variant attributes (e.g. data-variant) used in class mode
DISALLOWED_STATE_ATTRIBUTE State attributes (e.g. data-state, aria-*) used in class mode
INVALID_VARIANT_VALUE Variant value violates valueNaming in data mode
INVALID_STATE_VALUE State value violates valueNaming in data mode
DYNAMIC_CLASS_UNRESOLVED Class value is dynamic and cannot be verified statically
CLASSLESS_TAG_NOT_ALLOWED A non-allowlisted HTML tag has no class attribute
UNBALANCED_HTML HTML opening/closing tags are not balanced
MULTIPLE_ROOT_ELEMENTS Multiple root elements detected in root mode
MAX_DEPTH_EXCEEDED Safety limit exceeded; returned as status: "blocked", not as a SpiraCSS HTML-depth rule

Notes:

  • In --selection mode, classless roots are also checked; non-allowlisted tags without a class report CLASSLESS_TAG_NOT_ALLOWED, while classed descendants are validated as independent roots
  • data-* / aria-* are validated only when they match the reserved keys (variant.dataKeys / state.dataKey / state.ariaKeys)
  • Data value naming is validated against selectorPolicy.valueNaming and variant/state.valueNaming
  • Classes matching stylelint.base.external.classes / stylelint.base.external.prefixes are treated as external (excluded from base checks)
  • If the first token is an external class and a non-external class appears later, it results in INVALID_BASE_CLASS (Block/Element must come first). Elements with only external classes are allowed
  • When variant.mode=class and state.mode=class, state cannot be separated, so all modifiers are treated as variants
  • Error message text can change; do not depend on exact strings

spiracss-html-format

Formats HTML by inserting placeholder classes to normalize SpiraCSS structure.

Basic usage

Terminal window
# Read from file and write to another file
yarn spiracss-html-format path/to/file.html -o formatted.html
# Read from file and output to stdout
yarn spiracss-html-format path/to/file.html
# Read from stdin and write to a file
cat file.html | yarn spiracss-html-format --stdin -o formatted.html

Options

Option Description
--stdin Read HTML from stdin
-o, --output PATH Output file path (defaults to stdout)

The output attribute follows htmlFormat.classAttribute in spiracss.config.js (default: class).
Set htmlFormat.classAttribute to className if you want className output.
Internally, class / className are temporarily converted to data-spiracss-classname and restored on output.

Inserted classes

Recursively walks all descendants and normalizes them into a Block > Element structure.

  • Elements with children -> prepend a Block placeholder
  • Leaf elements -> prepend an Element placeholder
  • Elements with an existing Block name -> keep the name and process descendants
  • Elements with an Element name but with children -> convert to Block form (e.g. title -> title-box)

Note: For the root element, Element -> Block conversion is not performed; instead, a Block placeholder is prepended (e.g. block-box title), even for names that are neither Block nor Element.

Placeholder names change based on blockCase / elementCase (configured independently):

Case Block placeholder Element placeholder
kebab (default) block-box element
camel blockBox element
pascal BlockBox Element
snake block_box element

Note:

  • Element names are always a single word. elementCase=camel allows only a single lowercase word (e.g. element), and elementCase=pascal allows only a single capitalized word (e.g. Element); internal capitals like bodyText / BodyText are not allowed
  • If you set customPatterns, ensure the placeholders (block-box / element) still match your naming rules

Limitations

HTML that includes template syntax (EJS <% %>, Nunjucks {{ }} / {% %} / {# #}, Astro frontmatter, etc.) is skipped.
These constructs can be broken by HTML parsing, so only use static HTML fragments.

For placeholder insertion, JSX class / className are supported only when the binding is static: string literals, template literals whose ${} segments are static member access or string literals, or member access like styles.foo / styles['foo'] / styles["foo"]. If jsxClassBindings.memberAccessAllowlist is set, only the listed base identifiers are treated as class sources, and chained access like styles.layout.hero is treated as dynamic. If any dynamic binding is present (conditions, props such as props.className, function calls, non-static ${} segments), the entire HTML is skipped. When formatting JSX/TSX, bindings are normalized to plain class strings for placeholder insertion, so treat the output as scaffolding (do not overwrite CSS Modules sources).

When template syntax is detected:

  • Stdout mode (no -o): output the original HTML and emit a warning to stderr
  • File output mode (-o): skip writing the file and emit a warning to stderr (prevents mtime changes)
  • Behavior is undefined when fragment HTML is missing closing tags for <template> / <textarea> (no explicit detection is performed)

Conversion spec

Conversion example

<!-- Selected HTML -->
<section class="hero-section">
<h1 class="title">Welcome</h1>
<p class="body">Introduction text...</p>
<div class="feature-card">
<h2 class="heading">Feature</h2>
</div>
<div class="cta-box">
<a class="link" href="#">Learn more</a>
</div>
</section>

Generates SpiraCSS-style SCSS:

hero-section.scss (root Block):

@use "@styles/partials/global" as *;
@use "sass:meta";
// @assets/css/index.scss
@scope (.hero-section) {
:scope {
@include meta.load-css("scss");
@include breakpoint-up(md) {
// layout mixin
}
> .title {
@include breakpoint-up(md) {
// layout mixin
}
}
> .body {
@include breakpoint-up(md) {
// layout mixin
}
}
> .feature-card {
// @rel/scss/feature-card.scss
@include breakpoint-up(md) {
// child component layout
}
}
> .cta-box {
// @rel/scss/cta-box.scss
@include breakpoint-up(md) {
// child component layout
}
}
// --shared ----------------------------------------
// --interaction -----------------------------------
// @at-root & {
// }
}
}

scss/feature-card.scss (child Block):

@use "@styles/partials/global" as *;
// @rel/../hero-section.scss
.feature-card {
@include breakpoint-up(md) {
// layout mixin
}
> .heading {
@include breakpoint-up(md) {
// layout mixin
}
}
// --shared ----------------------------------------
// --interaction -----------------------------------
// @at-root & {
// }
}

scss/cta-box.scss (child Block):

@use "@styles/partials/global" as *;
// @rel/../hero-section.scss
.cta-box {
@include breakpoint-up(md) {
// layout mixin
}
> .link {
@include breakpoint-up(md) {
// layout mixin
}
}
// --shared ----------------------------------------
// --interaction -----------------------------------
// @at-root & {
// }
}

scss/index.scss (child Block index file):

@use "cta-box";
@use "feature-card";
your-component/
├─ hero-section.scss -> root Block
├─ scss/
│ ├─ cta-box.scss -> child Block
│ ├─ feature-card.scss -> child Block
│ └─ index.scss -> auto-merged via @use
└─ your-template.html

Supported templates

Note: This section describes SCSS generation.
For placeholder insertion, see the limitations above.

Template Support
Plain HTML Fully supported
Astro Frontmatter removed automatically
EJS <% ... %> removed automatically
Nunjucks {{ }} / {% %} / {# #} removed automatically
JSX Extracts static classes from class / className
Vue / Svelte Removes attributes like v-* / :prop (in some cases, v-bind:class may leave :class behind)

Template syntax is stripped using regular expressions.

  • <%...%> (EJS)
  • {{...}} / {%...%} / {#...#} (Nunjucks)
  • JSX comments {/*...*/}
  • JSX fragments <>...</>
  • <script>...</script> / <style>...</style> blocks
  • dangerouslySetInnerHTML attributes
  • attribute spreads like {...foo}
  • template literal interpolations ${...} (static member access or string literals inside class / className may still be extracted)

Generic {...} patterns are not removed, and static class names are extracted from class / className.

Block/Element detection

The first token in the class attribute is treated as the base class.
It is treated as a Block only when the first token matches blockCase (or customPatterns.block).
Put the class you want to treat as the Block/Element first.

blockCase Block examples elementCase Element examples
kebab (default) hero-section, feature-card kebab (default) title, body
camel heroSection, featureCard camel title, body
pascal HeroSection, FeatureCard pascal Title, Body
snake hero_section, feature_card snake title, body

Note:

  • Element names are always a single word. elementCase=camel allows only a single lowercase word (e.g. title), and elementCase=pascal allows only a single capitalized word (e.g. Title); names like bodyText / BodyText that contain multiple words are not allowed
  • If you set customPatterns, those patterns take priority
  • When using customPatterns, ensure placeholders (block-box / element) still match your naming rules
  • Classes starting with -, _, or u- are treated as Modifier/Utility and cannot be base classes (even if they match customPatterns)

Dynamic class limitations

  • Static classes inside Vue/Svelte :class bindings are not extracted (place them in class="..." instead). In some cases, v-bind:class may leave :class behind.
  • Dynamically appearing class names are not tracked
  • JSX class / className: SCSS generation extracts static class names from string literals, template literal static parts plus string literals or member access inside ${}, and member access (e.g. styles.foo, styles['foo'], styles["foo"]). When jsxClassBindings.memberAccessAllowlist is set, only the listed base identifiers are treated as class sources; chained access (e.g. styles.layout.hero) is treated as dynamic. Dynamic expressions are dropped.
  • Placeholder insertion skips JSX bindings that include dynamic expressions (e.g. props.className, foo && 'bar', non-static ${} segments).

Configuration

All CLI commands read spiracss.config.js. See spiracss.config.js for details. If package.json has "type": "module", use export default instead of module.exports.

Because the HTML CLI is a CJS bundle, it cannot load ESM config when Node is launched with --disallow-code-generation-from-strings. If possible, switch to module.exports or remove the flag. In "type": "module" projects, spiracss.config.js cannot be CJS, so you effectively need to remove the flag (no automatic .cjs / .mjs discovery).

If spiracss.config.js exists but cannot be loaded, the CLI exits with an error (check the config syntax and type: "module").

See spiracss.config.js for full configuration options.