Tailwind-first Next.js Image component with automatic sizes inference.
npm install tw-next-image

Tailwind-first Next.js image component with automatic sizes inference.
See DOCS.md for full examples and API reference.
The next/image component requires a [sizes][mdn-sizes] attribute to serve optimally-sized images. Without it,
Next.js defaults to 100vwโmeaning a 64px thumbnail requests the same massive image as a full-width hero. This wastes
bandwidth and hurts Core Web Vitals.
The problem: crafting sizes by hand is tedious. Every responsive image needs a media query string that mirrors your
CSS breakpoints:
``tsx`
// Manual sizes for a responsive image ๐ด
tw-next-image eliminates this busywork. It parses your Tailwind classes and infers the correct sizes
automatically:
`tsx`
// Same result, zero mental overhead ๐
// โ sizes="(min-width: 1024px) 120px, 100px"
Further reading
- next/image responsive behavior discussion
- Tailwind + next/image integration request
- Inefficient srcset generation issue
- Deep dive: the sizes attribute in Next.js
[mdn-sizes]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes
`bash`
npm install tw-next-imageor
pnpm add tw-next-imageor
yarn add tw-next-imageor
bun add tw-next-image
Requirements: Next.js โฅ13, React โฅ18
`tsx
import { SmartImage } from "tw-next-image";
// sizes inferred from className
// โ sizes="44px"
// Responsive breakpoints
// โ sizes="(min-width: 1024px) 120px, 100px"
`
SmartImage wraps next/image with fill modeโensure the wrapper has height via size-, h-, aspect-*, ormin-w-
inline styles. Inference also respects /max-w- and min-h-/max-h- constraints, and usesstyle.aspectRatio for height-only layouts.
If your app uses a custom tailwind-merge config, inject it via createSmartImage:
`tsx
import { createSmartImage } from "tw-next-image";
import { customTwMerge } from "./tailwind/merge";
export const SmartImage = createSmartImage({ cx: customTwMerge });
`
Use inferImageSizes without the React component:
`tsx
import { inferImageSizes } from "tw-next-image/infer-sizes";
inferImageSizes({ className: "w-75" });
// โ "300px"
inferImageSizes({ className: "size-25 lg:size-30" });
// โ "(min-width: 1024px) 120px, 100px"
``