VueJS/Tailwind CSS/VITE: Use environment variables as color of Tailwind theme
P粉174151913
P粉174151913 2023-08-26 14:31:22
0
1
355

I have a VueJS setup with Vite, Tailwind CSS and postcss and would like to define different colors using variables in the .env.name file so that I can apply it based on where the code is deployed Different color themes. < /p>

I tried using a file containing .env

VITE_COLOR="FF0000"

And import

in tailwind.config.js
... theme: { colors: { primary: import.meta.env.COLOR } } ... 

However, I get the following error:

Syntax error: 'import.meta' cannot be used outside a module

What do I need to change to make it work, or is there a better way?

P粉174151913
P粉174151913

reply all (1)
P粉212114661

Tailwind configurations are CommonJS files (not modules), so you can't use ES6 features likeimport

You can install a package nameddotenv

npm i dotenv

Needs to be placed above the tailwind configuration file, for example

require('dotenv').config() module.exports = {/** */}

Create color variables in.env. Note that since we require it to be outside the scope of Vite, it may not be prefixed withVITE_

ANY_COLOR='#ffc8dd'

Now you can access it in the tailwind configuration

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

This will workbutif you change the colors in the.envfile you will need to rebuild the styles again. If it works for you (one deployment - one color anyway) - great. I personally would suggest another solution based on CSS variables -CanIUse link

Define variables in a CSS file or createstyletagsinsidetags inindex.html

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

and in configuration

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

That's it - no extra packages, extra work, if you change a CSS variable, the changes will be applied instantly - even in production because we use CSS features

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!