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

如何在JS文件中获取Tailwind配置文件中的自定义颜色?

在JS文件中获取Tailwind自定义颜色的几种方法

方法1:直接导入tailwind.config.js

这是最直接的方式,你可以直接把配置文件导入到JS中,读取对应的颜色值:

// 导入你的Tailwind配置文件
import tailwindConfig from './tailwind.config.js';

// 获取自定义颜色
const primaryColor = tailwindConfig.theme.extend.colors.primary;
const gpColor = tailwindConfig.theme.extend.colors.gp;

// 如果你的颜色是定义在theme.colors而非extend里,就改成:
// const primaryColor = tailwindConfig.theme.colors.primary;

方法2:使用Tailwind的resolveConfig工具

如果需要同时获取Tailwind默认颜色和自定义颜色(合并两套配置),可以用官方提供的resolveConfig工具:

  1. 先安装依赖:
npm install @tailwindcss/resolve-config
  1. 在JS文件中使用:
import resolveConfig from '@tailwindcss/resolve-config';
import tailwindConfig from './tailwind.config.js';

// 合并默认配置和自定义配置
const fullConfig = resolveConfig(tailwindConfig);

// 获取颜色,包括默认和自定义的
const primaryColor = fullConfig.theme.colors.primary;
const defaultBlue = fullConfig.theme.colors.blue[500]; // Tailwind默认颜色

方法3:通过CSS变量读取

先把自定义颜色定义成全局CSS变量,再在JS中读取:

  1. 在全局样式文件(比如src/index.css)中添加:
@tailwind base;
@tailwind components;
@tailwind utilities;

/* 定义自定义颜色为CSS变量,也可用Tailwind的theme指令自动读取配置,避免重复写值 */
:root {
  --color-primary: theme('colors.primary');
  --color-gp: theme('colors.gp');
  --color-bl: theme('colors.bl');
  --color-airtel: theme('colors.airtel');
  --color-robi: theme('colors.robi');
  --color-teletalk: theme('colors.teletalk');
}
  1. 在JS文件中读取:
// 获取单个颜色
const primaryColor = getComputedStyle(document.documentElement).getPropertyValue('--color-primary').trim();

// 封装成函数批量获取
function getCustomColor(colorName) {
  return getComputedStyle(document.documentElement).getPropertyValue(`--color-${colorName}`).trim();
}

const gpColor = getCustomColor('gp');

如果开启了darkMode,你可以在.dark类下重新定义CSS变量,JS会自动读取当前模式下的颜色值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:01:24