VueJS/Tailwind CSS/VITE: Use environment variables as color of Tailwind theme
P粉174151913
2023-08-26 14:31:22
<p>I have a VueJS setup with Vite, Tailwind CSS and postcss and would like to define different colors using variables in the <code>.env.name</code> file so that I can apply it based on where the code is deployed Different color themes. < /p>
</p><p>I tried using a file containing <code>.env</code></p>
<pre class="brush:php;toolbar:false;">VITE_COLOR="FF0000"</pre>
<p>And import</p> in <code>tailwind.config.js</code>
<pre class="lang-js prettyprint-override"><code>...
theme: {
colors: {
primary: import.meta.env.COLOR
}
}
...
</code></pre>
<p>However, I get the following error: </p>
<blockquote>
<p>Syntax error: 'import.meta' cannot be used outside a module</p>
</blockquote>
<p>What do I need to change to make it work, or is there a better way? </p>
Tailwind configurations are CommonJS files (not modules), so you can't use ES6 features like
import
You can install a package named dotenv
Needs to be placed above the tailwind configuration file, for example
Create color variables in
.env
. Note that since we require it to be outside the scope of Vite, it may not be prefixed withVITE_
Now you can access it in the tailwind configuration
This will work but if you change the colors in the
.env
file 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 linkDefine variables in a CSS file or create
style
tagsinside
tags in
index.htmland in configuration
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