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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay