برنامه نویسی
WANTED: VSCode و/یا افزونه زیباتر برای کاهش رنج ویرایش ویژگیهای کلاس در پروژه Tailwind
اگر عنوان این پست با شما صحبت می کند، کنجکاو هستم که چه نوع جریان کاری ممکن است برای برخورد با oodles و oodles از کلاس ها در یک عنصر واحد، اغلب در میان بسیاری دیگر در یک مؤلفه ایجاد کرده باشید.
فکر کردم کارهایی را که در حال حاضر انجام میدهم به اشتراک بگذارم، و شاید دیگران بتوانند به من نشان دهند که چگونه آن را متفاوت انجام میدهند. یا شاید حداقل بتوانم با مثال هایم به شخص دیگری الهام بخشم:
import { ComponentProps, useState } from 'react'
import { twMerge } from 'tailwind-merge'
// A TypeScript template literal tag function for Tailwind classes
// Usually imported from a folder of other utilities
function tw(strings: TemplateStringsArray, ...values: any[]) {
return String.raw({ raw: strings }, ...values)
}
// Sometimes this is exported from a file of its own if things get hairy
// For even simpler components, this wouldn't even be a function
// and instead I'd just have the object itself, named `classNames` or something
function getClassNames({ someCondition = false }) {
return {
container: twMerge(
someCondition &&
`
bg-red-400
text-red-600
`,
`
flex
h-full
flex-col
items-center
justify-center
`,
),
someSemanticallyNamedElement: tw`
text-lg
`,
}
}
// Most of my components still accept a className prop,
// so I merge it with the lovely `tailwind-merge` library
export function MyComponent({
className,
...otherProps
}: ComponentProps<'div'>) {
const [someCondition, setSomeCondition] = useState(false)
const classes = getClassNames({ someCondition })
return (
<div
// ⛙ Merge the classes. The incoming classes take precedence
// but sometimes I pass them first if I need to ensure
// specific classes can't be overridden
className={twMerge(classes.container, className)}
{...otherProps}
>
<div className={classes.someSemanticallyNamedElement}>Hello, world!</div>
</div>
)
}