如何在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工具:
- 先安装依赖:
npm install @tailwindcss/resolve-config
- 在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中读取:
- 在全局样式文件(比如
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'); }
- 在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
相关产品推荐
相关产品推荐

