npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

stylize-css

v1.0.1

Published

Bidirectional CSS/SCSS/SASS to JSON converter. Parse stylesheets to structured JSON and generate back while preserving variables, nesting, sections, and comments.

Downloads

204

Readme

stylize-css

Bidirectional CSS/SCSS/SASS to JSON converter - Parse stylesheets into structured JSON and generate back while preserving variables, nesting, sections, and comments.

Perfect for design system automation, theme generation, style validation, and design token extraction.


✨ Features

  • Multi-format support - CSS, SCSS, SASS, JSON
  • Bidirectional conversion - CSS ↔ JSON, SCSS ↔ JSON, SASS ↔ JSON (lossless)
  • Preserve structure - Variables, nested selectors, @media queries, mixins, functions
  • Section detection - Extract styles by BEGIN/END markers
  • Comment preservation - Keep comments in roundtrip conversions
  • CLI tool - Command-line utility for quick conversions
  • Programmatic API - Use in Node.js applications
  • TypeScript support - Full type definitions included
  • 100% test coverage - 156 comprehensive tests
  • Zero dependencies - Only PostCSS and PostCSS-SCSS

📦 Installation

npm install stylize-css

Or globally for CLI:

npm install -g stylize-css

🚀 Quick Start

CLI Usage

# Convert SCSS to JSON
stylize-css input.scss --to-json -o output.json

# Convert JSON to SCSS
stylize-css styles.json --to-scss -o styles.scss

# Convert to CSS
stylize-css input.scss --to-css -o style.css

# Extract specific section
stylize-css style.scss --section "Colors" --to-json

# Pretty print JSON output
stylize-css input.scss --to-json --pretty

# Stdin/stdout
cat style.scss | stylize-css --to-json | jq .

Programmatic Usage

import { toJSON, toSCSS } from 'stylize-css';

const scss = `
$primary: #0a1f40;
$secondary: #ff6b6b;

.button {
  background: $primary;
  padding: 10px 20px;
  
  &:hover {
    background: $secondary;
  }
}
`;

// Parse to JSON
const json = toJSON(scss, { 
  detectSections: true,
  preserveComments: true 
});

console.log(json);

// Generate back to SCSS
const output = toSCSS(json, { 
  indent: 2,
  sortProperties: true 
});

console.log(output);

📖 Complete Examples

Example 1: Extract Design Tokens

import { toJSON } from 'stylize-css';

const scssString = `
$primary-color: #0a1f40;
$secondary-color: #ff6b6b;
$spacing-sm: 8px;
$spacing-md: 16px;
$spacing-lg: 24px;
`;

const json = toJSON(scssString);

// Extract tokens
const tokens = Object.entries(json.variables).map(([name, node]) => ({
  name,
  value: node.value
}));

console.log(tokens);
/* Output:
[
  { name: '$primary-color', value: '#0a1f40' },
  { name: '$secondary-color', value: '#ff6b6b' },
  { name: '$spacing-sm', value: '8px' },
  ...
]
*/

Example 2: Modify Styles Programmatically

import { toJSON, toSCSS } from 'stylize-css';

const scss = `
.card {
  background: white;
  border: 1px solid #ccc;
}

.card.active {
  background: blue;
}
`;

const json = toJSON(scss);

// Modify the JSON
json.selectors['.card'].properties['background'].value = '#f5f5f5';
json.selectors['.card'].properties['border'].value = '2px solid #999';

// Generate updated SCSS
const updated = toSCSS(json);
console.log(updated);

Example 3: Extract Section-Based Styles

import { toJSON } from 'stylize-css';

const scss = `
/* stylize-begin:Colors */
$primary: #0a1f40;
$secondary: #ff6b6b;
/* stylize-end:Colors */

/* stylize-begin:Typography */
$font-size-base: 16px;
$font-family: 'Segoe UI', sans-serif;
/* stylize-end:Typography */

.button {
  font-size: $font-size-base;
  color: $primary;
}
`;

const json = toJSON(scss, { detectSections: true });

console.log(json.sections['Colors']);
console.log(json.sections['Typography']);

Example 4: Format Conversion (SASS → SCSS → CSS)

import { toJSON, toSCSS } from 'stylize-css';

// SASS input (indented syntax)
const sassInput = `
$primary: #0a1f40

.button
  background: $primary
  padding: 10px
  
  &:hover
    opacity: 0.8
`;

// Convert SASS → JSON
const json = toJSON(sassInput, { format: 'sass' });

// Generate SCSS
const scss = toSCSS(json);

// Generate plain CSS
const css = toSCSS(json, { format: 'css' });

console.log(scss);  // SCSS with variables and nesting
console.log(css);   // Plain CSS with expanded selectors

Example 5: Validate and Standardize Styles

import { toJSON, toSCSS } from 'stylize-css';

function validateAndStandardize(cssString) {
  const json = toJSON(cssString);
  
  // Validate: check for unused variables
  const usedVars = new Set();
  Object.values(json.selectors).forEach(selector => {
    Object.values(selector.properties).forEach(prop => {
      const matches = prop.value.match(/\$\w+/g);
      if (matches) matches.forEach(v => usedVars.add(v));
    });
  });
  
  const unused = Object.keys(json.variables).filter(v => !usedVars.has(v));
  console.log('Unused variables:', unused);
  
  // Standardize: sort properties and format nicely
  return toSCSS(json, { 
    sortProperties: true,
    indent: 2 
  });
}

🛠️ API Reference

toJSON(input, options?)

Parse CSS/SCSS/SASS string to JSON object.

Parameters:

  • input (string) - CSS/SCSS/SASS stylesheet string
  • options (object, optional):
    • detectSections (boolean) - Detect BEGIN/END section markers (default: false)
    • preserveComments (boolean) - Keep comments in output (default: true)
    • resolveVariables (boolean) - Replace $variables with their values (default: false)
    • flattenNested (boolean) - Flatten nested selectors (default: false)
    • format (string) - Input format: 'css' | 'scss' | 'sass' (auto-detect by default)

Returns: JSON object with structure:

{
  variables: { [name]: { value, line, column } },
  selectors: { [selector]: { properties: { [prop]: { value } } } },
  mediaQueries: { [query]: { selectors } },
  sections: { [name]: { content, rules } },
  comments: string[]
}

toSCSS(json, options?)

Generate CSS/SCSS/SASS from JSON object.

Parameters:

  • json (object) - Parsed stylesheet JSON
  • options (object, optional):
    • format (string) - Output format: 'css' | 'scss' | 'sass' (default: 'scss')
    • indent (number) - Spaces per indentation level (default: 2)
    • sortProperties (boolean) - Sort properties alphabetically (default: false)
    • preserveComments (boolean) - Include comments (default: true)

Returns: Formatted stylesheet string


💻 CLI Reference

Commands

stylize-css <input> [options]
stylize <input> [options]

Input/Output Options

-o, --output FILE        Output file (default: stdout)
--pretty                 Pretty print JSON output

Format Options

--from-css              Treat input as CSS (default: auto-detect)
--from-scss             Treat input as SCSS
--from-sass             Treat input as SASS

--to-json               Output JSON (default)
--to-css                Output plain CSS
--to-scss               Output SCSS
--to-sass               Output SASS

Parse Options

--detect-sections       Detect BEGIN/END section markers
--preserve-comments     Keep comments (default: true)
--resolve-variables     Replace $variables with values
--flatten-nested        Flatten nested selectors
--include-source-map    Add source location info

Generate Options

--indent N              Indentation spaces (default: 2)
--sort-properties       Sort properties alphabetically

Help

stylize-css --help      Show help
stylize-css -h          Show help

📊 Real-World Use Cases

Design System Automation

Extract design tokens from SCSS files and generate theme files automatically.

Theme Generation

Modify JSON representation of styles and regenerate stylesheets in multiple formats.

Style Validation

Analyze stylesheet structure to find unused variables, detect code style violations.

Format Migration

Convert between CSS, SCSS, and SASS formats while preserving all features.

Static Analysis

Parse stylesheets for programmatic analysis without regex parsing.


🧪 Testing

# Run all tests
npm test

# Run in watch mode
npm run test:watch

# Generate coverage report
npm run test:coverage

Test Coverage:

  • 45 CSS → JSON tests
  • 39 SCSS → JSON tests
  • 24 SASS → JSON tests
  • 36 JSON → CSS/SCSS tests
  • 12 Options configuration tests
  • Total: 156 tests, 100% passing

🔧 Development

# Install dependencies
npm install

# Build TypeScript
npm run build

# Format code
npm run format

# Lint code
npm run lint

# Watch mode
npm run dev

📝 License

MIT License - See LICENSE file for details


🤝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/your-feature
  3. Add tests for new functionality
  4. Ensure all tests pass: npm test
  5. Commit with meaningful messages
  6. Push to your branch
  7. Submit a pull request

📧 Support

  • Repository: https://gitlab.com/e.kacaj/css-scss-json-converter
  • Issues: https://gitlab.com/e.kacaj/css-scss-json-converter/issues
  • Author: Edmond Kacaj [email protected]

For detailed documentation, see USAGE.md