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

VueJS+Vite+Tailwind CSS如何用环境变量配置主题颜色?

解决方案

错误原因

import.meta.env 是浏览器/ES模块环境的API,而 tailwind.config.js 默认以CommonJS模块模式运行在Node.js环境中,因此无法直接使用这个语法,这就是你遇到 SyntaxError 的原因。

修复步骤

  1. 修改tailwind配置中的变量获取方式
    直接使用Node.js的process.env访问Vite注入的环境变量(Vite会自动把所有带VITE_前缀的变量注入到process.env中):

    /** @type {import('tailwindcss').Config} */
    export default {
      content: [
        "./index.html",
        "./src/**/*.{vue,js,ts,jsx,tsx}",
      ],
      theme: {
        extend: {
          colors: {
            // 拼接#号,同时设置默认值防止变量未定义
            primary: `#${process.env.VITE_COLOR || 'FF0000'}`
          }
        },
      },
      plugins: [],
    }
    
  2. 确保.env文件变量格式正确
    你的.env(或对应环境的.env.development/.env.production)文件中变量必须以VITE_开头,比如:

    VITE_COLOR="FF0000"
    

更优实践:多主题变量管理

如果需要定义多个主题色,建议在项目中单独维护一个主题配置文件,再导入到tailwind配置中:

  1. 在src目录下创建theme.config.js:
    export const themeColors = {
      primary: `#${process.env.VITE_COLOR || 'FF0000'}`,
      secondary: `#${process.env.VITE_SECONDARY_COLOR || '00FF00'}`,
      accent: `#${process.env.VITE_ACCENT_COLOR || '0000FF'}`
    }
    
  2. 修改tailwind.config.js导入这个配置:
    import { themeColors } from './src/theme.config.js'
    
    /** @type {import('tailwindcss').Config} */
    export default {
      content: [
        "./index.html",
        "./src/**/*.{vue,js,ts,jsx,tsx}",
      ],
      theme: {
        extend: {
          colors: themeColors
        },
      },
      plugins: [],
    }
    

    注意:如果你的项目package.json中没有设置"type": "module",需要把tailwind.config.js改名为tailwind.config.mjs,否则Node会报错无法识别import语法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:42:40