DEV Community

Kay Gosho
Kay Gosho

Posted on

7 3

convert JS Object to CSS in command

image

I found Styled Component is much convenient for me to write styles with React.

However, I already wrote a lot of styles with JS object, using jss. So I need to convert JSS to CSS.

I wrote a tiny script, which is a set of perl one liners, and call the command from Vim.

~/bin/obj2style

#!/bin/bash

perl -pe 's/ +$//g' \
    | perl -pe 's/ as .+//g' \
    | perl -pe 's/([A-Z])/-\L\1/g' \
    | perl -pe 's/^_//' \
    | perl -pe 's/"([a-z]+)"$/\1/g' \
    | perl -pe "s/'([a-z]+)'$/\1/g" \
    | perl -pe 's/([0-9]+),?$/\1px/g' \
    | perl -pe 's/,?$/;/'
Enter fullscreen mode Exit fullscreen mode

(More elegant RegExp would exist but least effort here)

Test:

~> echo fontSize: 12 | obj2style 
font-size: 12px;

~> echo fontSize: 'large' | obj2style 
font-size: large;

~> echo "fontSize: 'large', " | obj2style 
font-size: large;

~> echo "fontWeight: 'bold' as 'bold'" | obj2style 
font-weight: bold;
Enter fullscreen mode Exit fullscreen mode

Then, use that command in vim!

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo πŸ“Šβœ¨

Top comments (4)

Collapse
 
andy profile image
Andy Zhao (he/him) β€’

Hey @maestromac right up your alley on this, especially with Preact.

Collapse
 
maestromac profile image
Mac Siri β€’

Is there an advantage to write these kind of script in perl as supposed to vim-script?

Collapse
 
acro5piano profile image
Kay Gosho β€’

Perl's Regular Expression is easy to write because it implements POSIX. In terms of performance vim-script may be better as calling external process is usually cost.

Collapse
 
vlasales profile image
Vlastimil Pospichal β€’
:'<,'>s/\([A-Z]\)/-\l\1/g

Image of PulumiUP 2025

Transform Your Cloud Infrastructure

Join PulumiUP 2025 on May 6 for Expert Insights & Demos.

Register Now

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay