Home > database >  VueJS/Tailwindcss/VITE use env variables as colors for tailwind theme
VueJS/Tailwindcss/VITE use env variables as colors for tailwind theme

Time:08-24

I got a VUEJS setup with vite, tailwindcss and postcss and would like to define different colors depending on variables within a .env.name file in order to use different color themes depending where the code is deployed.

I tried with a .env file containing

VITE_COLOR="FF0000"

and an import within the tailwind.config.js

...
theme: {
    colors: {
       primary: import.meta.env.COLOR
    }
}
...

but i get the following error: SyntaxError: Cannot use 'import.meta' outside a module

What do i have to change or is there even a better way?

CodePudding user response:

Tailwind config is CommonJS file (not module) so you cannot use ES6 features like import

You can install package called dotenv

npm i dotenv

Require it on top of your tailwind config file like

require('dotenv').config()

module.exports = {/** */}

create color variable in .env. Note as we require it out of Vite's scope it may not be prefixed with VITE_

ANY_COLOR='#ffc8dd'

Now you can access it in tailwind config

theme: {
    colors: {
       primary: process.env.ANY_COLOR
    }
}

This will work BUT if you change color in .env file you need to rebuild your styles again. If it is OK for you (one deployment - one color anyway) - fine. I personally would suggest another solution based on CSS variables - link to CanIUse

Define variable in CSS file or create style tag within <head> tag in index.html

:root {
    --theme-color: #ffc8dd;
}

and in config

theme: {
    colors: {
       primary: 'var(--theme-color)'
    }
}

And that's it - no extra packages, extra work and if you change CSS variable, changes will be applied on the fly - even in production as we are using CSS functionality

  • Related