Tailwind CSS가 순환 종속성을 감지하는 방법

Patricia Arquette
풀어 주다: 2024-10-09 06:19:02
원래의
624명이 탐색했습니다.

How Tailwind CSS detects circular dependancy.

이 글에서는 replacementAtApply에서 발생하는 오류를 분석합니다. 이 오류는 순환 종속성 감지에 관한 것입니다.

walk(rule.nodes, (child) => {
  if (child !== node) return
  throw new Error(
   `You cannot \`@apply\` the \`${candidate}\` utility here because it creates a circular dependency.`,
   )
})
로그인 후 복사

이 오류와 관련된 코드에 대한 높은 수준의 개요입니다.

걷기 — 재귀 함수:

걷기부터 시작해 보세요:

export function walk(
   ast: AstNode[],
   visit: (
     node: AstNode,
     utils: {
     parent: AstNode | null
     replaceWith(newNode: AstNode | AstNode[]): void
     context: Record<string, string>
   },
 ) => void | WalkAction,
 parent: AstNode | null = null,
 context: Record<string, string> = {},
) {
 for (let i = 0; i < ast.length; i++) {
   let node = ast[i]
  // We want context nodes to be transparent in walks. This means that
   // whenever we encounter one, we immediately walk through its children and
   // furthermore we also don't update the parent.
 if (node.kind === 'context') {
   walk(node.nodes, visit, parent, { …context, …node.context })
   continue
 }
let status = visit(node, {
   parent,
   replaceWith(newNode) {
   ast.splice(i, 1, …(Array.isArray(newNode) ? newNode : [newNode]))
   // We want to visit the newly replaced node(s), which start at the
   // current index (i). By decrementing the index here, the next loop
   // will process this position (containing the replaced node) again.
   i - 
 },
 context,
 }) ?? WalkAction.Continue
  // Stop the walk entirely
   if (status === WalkAction.Stop) return
  // Skip visiting the children of this node
   if (status === WalkAction.Skip) continue
  if (node.kind === 'rule') {
   walk(node.nodes, visit, node, context)
   }
 }
}
로그인 후 복사

walk는 ast.ts에 위치한 재귀 함수입니다.

node.kind === 'context'일 때 또는 node.kind === 'rule'일 때 자신을 재귀적으로 호출하며, 중단 조건은 상태를 기반으로 합니다

// Stop the walk entirely
if (status === WalkAction.Stop) return
// Skip visiting the children of this node
if (status === WalkAction.Skip) continue
로그인 후 복사

이제 조금 축소하여 Apply.ts의 걷기 기능 부근의 코드를 연구해 보겠습니다

// Verify that we don't have any circular dependencies by verifying that
// the current node does not appear in the new nodes.
walk(newNodes, (child) => {
 if (child !== node) return
  // At this point we already know that we have a circular dependency.
  //
  // Figure out which candidate caused the circular dependency. This will
 // help to create a useful error message for the end user.
 for (let candidate of candidates) {
   let selector = `.${escape(candidate)}`
    for (let rule of candidateAst) {
     if (rule.kind !== 'rule') continue
     if (rule.selector !== selector) continue
      walk(rule.nodes, (child) => {
     if (child !== node) return
      throw new Error(
       `You cannot \`@apply\` the \`${candidate}\` utility here because it creates a circular dependency.`,
       )
     })
    }
 }
})
로그인 후 복사

TailwindCSS 작성자는 필요한 경우 코드베이스 전체에 설명 주석을 추가했거나 추가 컨텍스트를 제공하는 것이 합리적입니다

댓글로.

회사 소개:

Think Throo에서는 오픈 소스 프로젝트에 사용되는 고급 코드베이스 아키텍처 개념을 가르치는 임무를 수행하고 있습니다.

Next.js/React에서 고급 아키텍처 개념을 연습하여 코딩 기술을 10배, 모범 사례를 배우고 프로덕션급 프로젝트를 구축하세요.

저희는 오픈 소스입니다 — https://github.com/thinkthroo/thinkthroo(별표를 주세요!)

웹 개발 및 기술 문서 작성 서비스도 제공합니다. 자세한 내용은 hello@thinkthroo.com으로 문의하세요!

참고자료:

  1. https://github.com/tailwindlabs/tailwindcss/blob/next/packages/tailwindcss/src/ast.ts#L70

  2. https://github.com/tailwindlabs/tailwindcss/blob/c01b8254e822d4f328674357347ca0532f1283a0/packages/tailwindcss/src/apply.ts

  3. https://stackoverflow.com/questions/71669246/need-help-using-apply-directive-in-tailwind-css

  4. https://github.com/tailwindlabs/tailwindcss/issues/2807

위 내용은 Tailwind CSS가 순환 종속성을 감지하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!