Home > Software design >  How can I create a dynamic CSS system in a Vue 3 app?
How can I create a dynamic CSS system in a Vue 3 app?

Time:05-24

I am working on an app that many different clients will use, but the "themes" can't be shared between clients because their color schemes are considered proprietary and confidential even though I'm aware that sounds absurd.

Right now, the colors are defined in the main App.vue component without the <style> instead of <style scoped>, and then downstream from there the components are all scoped.

The way it currently works is that I'm using CSS variables to define the colors and gradients.

I'm more or less looking for a solution that could do something like this pseudo-code:

const clientName = import.meta.env.CLIENT_NAME

if (clientName === 'abc') {

  :root {
    --background-color: #f3f3f3;
    --default-font-color: #000000;
    --primary: #8c4799;
    --secondary: #d22630;
    --gradient-primary: rgba(140, 71, 153, 0.2) 4.55%;
    --gradient-secondary: rgba(210, 38, 48, 0.02) 105.67%;
    --failure-color: #b94527;
    --badge1: #419bbe;
    --badge1text: #ffffff;
    --c-white: #f2f2f2;
  }

} else if (clientName === 'def') {
    --background-color: #0c0c0c;
    --default-font-color: #ffffff;
    --primary: #c1fc3d;
    --secondary: #d22630;
    --gradient-primary: rgba(110, 71, 153, 0.2) 3%;
    --gradient-secondary: rgba(190, 38, 48, 0.02) 50%;
    --failure-color: #b94527;
    --badge1: #419bbe;
    --badge1text: #ffffff;
    --c-white: #ffffff;
}

Keeping in mind that all of the downstream components use these variables and it's a pretty large app.

I'm using Vite for bundling if that makes a difference.

CodePudding user response:

You can create one .css file exporting these css variables for every client. Then, on your main.js entry point, you can import the file corresponding to that client:

const clientName = import.meta.env.CLIENT_NAME

import `@/assets/themes/${clientName}.css`;
  • Related