I am trying to set tailwind classes dynamically, but ran into an issue where colors defined in tailwind.config.cjs won’t be loaded if I call them from a function. Here is a simplified example.
+page.svelte
<script>
const getTeamName = () => {
return 'team1';
};
</script>
<div class={`bg-white text-teams-${getTeamName()}`}>Team 1</div>
<div class={`bg-white text-teams-team2`}>Team 2</div>
tailwind.config.cjs
const config = {
content: [
'./src/**/*.{html,js,svelte,ts}',
'./node_modules/flowbite-svelte/**/*.{html,js,svelte,ts}'
],
theme: {
extend: {
colors: {
teams: {
team1: '#e2012d',
team2: '#826818',
}
}
}
},
plugins: [require('flowbite/plugin')],
};
Screenshot of result
You can see team2 color is loading just fine, but team1 stays black (The color code is bright red). What’s interesting is that if I set the getTeamName return value to ‘team2’, the color will load. It seems to have something to do with the colors having been loaded or not? Not sure if this is a sveltekit issue or tailwind issue.
>Solution :
It seems like the tailwind cannot scan the class, because the getTeamName() is a runtime variable
try use
const getTeamName = (team) => {
// use a switch or if..else.. statement here
return 'text-teams-team1';
};
