/* The main method here is processTailwindSrcsetSizes. You can generate a sizes attribute using it based on tailwind style breakpointed sizes such as: "100vw md:500px" "200px md:300px xl:600px" "100vw" I use it in a React component by taking a sizes prop on the component, then passing that value into processTailwindSrcsetSizes then using that as the actual sizes attribute. */ import resolveConfig from 'tailwindcss/resolveConfig'; // Resolve correctly based on your codebase import tailwindConfig from '@/../tailwind.config.js'; const fullConfig = resolveConfig(tailwindConfig); export function isTailwindScreen( screen: string, ): screen is keyof typeof fullConfig.theme.screens { return screen in fullConfig.theme.screens; } export function processTailwindSrcsetSizes(sizes: string) { type TailwindSizesSize = { size: number; width: string; }; const convertedSizes = sizes .split(' ') .map((rule) => { const [screenOrSoleWidth, width] = rule.split(':'); if (screenOrSoleWidth && !width) { return { size: 0, width: screenOrSoleWidth, }; } if ( !screenOrSoleWidth || !width || !isTailwindScreen(screenOrSoleWidth) ) { return null; } return { size: parseInt(fullConfig.theme.screens[screenOrSoleWidth]), width: width, }; }) .filter((rule) => rule !== null) as TailwindSizesSize[]; if (!convertedSizes.length) { return null; } return convertedSizes .sort((a, b) => a.size - b.size) .map(({ size, width }) => (size === 0 ? width : `${size}w ${width}`)) .join(', '); }