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
Maintainers
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-cssOr 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 selectorsExample 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 stringoptions(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 JSONoptions(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 outputFormat 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 SASSParse 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 infoGenerate Options
--indent N Indentation spaces (default: 2)
--sort-properties Sort properties alphabeticallyHelp
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:coverageTest 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:
- Fork the repository
- Create a feature branch:
git checkout -b feature/your-feature - Add tests for new functionality
- Ensure all tests pass:
npm test - Commit with meaningful messages
- Push to your branch
- 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
