You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React-Vite项目的Tailwind CSS v4中使用环境变量?

在TailwindCSS的index.css中使用.env环境变量设置主题色

方案一:通过JS注入全局CSS变量后引用

  1. 在项目入口文件(如main.js/main.ts)中添加以下代码,将环境变量挂载到根元素的CSS变量:
document.documentElement.style.setProperty('--primary-color', import.meta.env.VITE_PRIMARY_COLOR);
document.documentElement.style.setProperty('--secondary-color', import.meta.env.VITE_SECONDARY_COLOR);
document.documentElement.style.setProperty('--action-color', import.meta.env.VITE_ACTION_COLOR);
  1. 修改index.css的主题配置,引用这些全局变量:
@import "tailwindcss";

@theme {
  --color-main: var(--primary-color);
  --color-secondary: var(--secondary-color);
  --color-action: var(--action-color);
}

方案二:直接在CSS中使用Vite环境变量

Vite支持在CSS中直接解析环境变量,只需用#{import.meta.env.变量名}的格式引用,修改index.css如下:

@import "tailwindcss";

@theme {
  --color-main: #{import.meta.env.VITE_PRIMARY_COLOR};
  --color-secondary: #{import.meta.env.VITE_SECONDARY_COLOR};
  --color-action: #{import.meta.env.VITE_ACTION_COLOR};
}

注意:环境变量名必须以VITE_开头(你的.env文件已符合要求),Vite才会将其注入到项目中。

内容的提问来源于stack exchange,提问作者Becca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:47:39