Referencing Tailwind Values in JavaScript
This article will show you how to access Tailwind configuration values in your JavaScript code with a Tailwind helper.
Step 1: Import resolveConfig
and Your Tailwind Configuration
To start, import two things: the resolveConfig
helper from Tailwind CSS and your Tailwind configuration file. The resolveConfig
helper is a special function provided by Tailwind that merges your configuration with the default Tailwind configuration to give you a complete configuration object.
Here's how you do it:
import resolveConfig from 'tailwindcss/resolveConfig'; import tailwindConfig from './tailwind.config.js';
Make sure that your Tailwind configuration file is correctly linked. It's named tailwind.config.js
by default and located in your project's root directory.
Step 2: Generate the Configuration Object
Once you have imported resolveConfig
and your Tailwind configuration, you can generate a fully merged configuration object. This object will contain all of Tailwind's default settings merged with your custom configurations.
const fullConfig = resolveConfig(tailwindConfig);
Step 3: Grab the Values
You can access any value now that you have the full configuration object.
For example, if you want to use specific width, breakpoint, or colors values defined in your Tailwind configuration, you can do so like this:
console.log(fullConfig.theme.colors.gray[300]); // Outputs: '#d1d5db' console.log(fullConfig.theme.screens.md); // Outputs: '768px' console.log(fullConfig.theme.boxShadow['2xl']); // Outputs: '0 25px 50px -12px rgba(0, 0, 0, 0.25)'
And to save you some time, here's the full snippet so you can copy and paste:
import resolveConfig from 'tailwindcss/resolveConfig' import tailwindConfig from './tailwind.config.js' const fullConfig = resolveConfig(tailwindConfig) console.log(fullConfig.theme.colors.gray[300]); // Outputs: '#d1d5db' console.log(fullConfig.theme.screens.md); // Outputs: '768px' console.log(fullConfig.theme.boxShadow['2xl']); // Outputs: '0 25px 50px -12px rgba(0, 0, 0, 0.25)'
Caution: Bundle Size
It's important to note that using resolveConfig
directly in your client-side JavaScript might increase your bundle size because it includes the entire Tailwind configuration along with Tailwind's default settings.
To avoid bloating your client-side bundle, consider using a build-time tool like babel-plugin-preval
to generate a static version of your configuration at build time.