Blog
buildDesignSystem fn in Tailwind CSS source code.

buildDesignSystem fn in Tailwind CSS source code.

In this article, we analyze buildDesignSystem function in Tailwind CSS source code.

DesignSystem type picked from design-system.ts

export type DesignSystem = {
  theme: Theme
  utilities: Utilities
  variants: Variants

  invalidCandidates: Set<string>

  // Whether to mark utility declarations as !important
  important: boolean

  getClassOrder(classes: string[]): [string, bigint | null][]
  getClassList(): ClassEntry[]
  getVariants(): VariantEntry[]

  parseCandidate(candidate: string): Candidate[]
  parseVariant(variant: string): Variant | null
  compileAstNodes(candidate: Candidate): ReturnType<typeof compileAstNodes>

  getVariantOrder(): Map<Variant, number>
  resolveThemeValue(path: string): string | undefined

  // Used by IntelliSense
  candidatesToCss(classes: string[]): (string | null)[]
}

At the time of writing this article, design-system.ts has about 144 LOC.

Let’s discuss how the values returned by DefaultMap utility function is used in designSystem.

let parsedVariants = new DefaultMap((variant) => parseVariant(variant, designSystem))
let parsedCandidates = new DefaultMap((candidate) =>
  Array.from(parseCandidate(candidate, designSystem)),
)
let compiledAstNodes = new DefaultMap<Candidate>((candidate) =>
  compileAstNodes(candidate, designSystem),
)

These variables are used in designSystem object as shown below:

parseCandidate(candidate: string) {
  return parsedCandidates.get(candidate)
},
parseVariant(variant: string) {
  return parsedVariants.get(variant)
},
compileAstNodes(candidate: Candidate) {
  return compiledAstNodes.get(candidate)
},

utilities and variants are the values returned by createUtilities and createVariants.

Keys such as candidatesToCss, getVariantOrder and resolveThemeValue have their function implementations that require furter analysis.

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com

My Github — https://github.com/ramu-narasinga

My website — https://ramunarasinga.com

My Youtube channel — https://www.youtube.com/@thinkthroo

Learning platform — https://thinkthroo.com

Codebase Architecture — https://app.thinkthroo.com/architecture

Best practices — https://app.thinkthroo.com/best-practices

Production-grade projects — https://app.thinkthroo.com/production-grade-projects

References:

  1. https://github.com/tailwindlabs/tailwindcss/blob/next/packages/tailwindcss/src/design-system.ts

  2. https://github.com/tailwindlabs/tailwindcss/blob/c01b8254e822d4f328674357347ca0532f1283a0/packages/tailwindcss/src/index.ts#L319