Convert a JavaScript Style Object to CSS Custom Properties with this Little Helper Tool

In a Next.js-based project I’m working I noticed this theme.js file which contains a JavaScript object that holds design tokens, defining what colors to use and such. As we are only using these values in CSS (via Styled Components) we decided on migrating away from it, and replace it with CSS Custom Properties. For this, I created a little helper tool.

The theme.js contents looked something like this (simplified):

const theme = {
    borderRadius: '15px',
    cardSpacing: {
        horizontal: '20px',
        vertical: '85px',
    },
    colors: {
        primaryBackground: '#FAFAF2',
        primaryButton: '#FFFFFF',
        primaryCard: '#FFFFFF',

        accent: '#2ea7a4',
        text: '#2f2f2f',
        textSecondary: '#707070',
        placeholder: '##959595',

        title: '#000',
        subTitle: 'rgba(255, 255, 244, 0.5)',
    },
};

export default theme;

Converted to Custom Properties, I want this:

--border-radius: 15px;
--card-spacing-horizontal: 20px;
--card-spacing-vertical: 85px;
--colors-primary-background: #FAFAF2;
--colors-primary-button: #FFFFFF;
--colors-primary-card: #FFFFFF;
--colors-accent: #2ea7a4;
--colors-text: #2f2f2f;
--colors-text-secondary: #707070;
--colors-placeholder: ##959595;
--colors-title: #000;
--colors-sub-title: rgba(255, 255, 244, 0.5);

~

To translate entries such as theme.colors.primaryCard to --colors-primary-card I decided to create a little helper tool. It automatically adds the required -- prefix, adjusts all camelCase occurrences to kebab-case, and plays nice with nested objects and (simple) arrays.

Perhaps this tool might also be of good use to you 🙂

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don\'t do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

BuymeaCoffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.