Skip to content

Read vanilla-extract stylesheet exports from ordinary modules - #973

Merged
owjs3901 merged 1 commit into
mainfrom
fix/vanilla-extract-theme-imports
Nov 17, 2026
Merged

owjs3901 merged 1 commit into
mainfrom
fix/vanilla-extract-theme-imports

Conversation

@owjs3901

@owjs3901 owjs3901 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to DOC-09. This is what #760 said would be "supported in a separate PR".

Problem

  • When an ordinary module (a .ts/.tsx, not .css.ts) imported vars from theme.css.ts and read vars.space, vars.colors.bg, etc. in style()/css()/JSX props, the build failed. The error message is `css()` cannot use `vars.space` at build time.
  • This happened even when theme.css.ts and tokens.ts resolved correctly.
  • Reproduced with a test on main.

Fix

  • When the import target is a vanilla-extract stylesheet (.css.ts/.css.js), the imported-constants reader (Modules::resolve_exports) extracts that file the same way the bundler does (extract_with_source_map). It reads the exports as literals from the extracted output code.
    • New file: imported_constants/stylesheet_exports.rs
    • Read through this path: the vars objects of createThemeContract/createTheme/createGlobalTheme, theme classes, createVar variables, style class names
    • So style({ margin: vars.space }) compiles to the same var(--space-…) name that the stylesheet's own CSS declares.
    • style([base, …]) also keeps the class the stylesheet generated.
  • The stylesheet import is kept so its CSS is loaded.
  • Dependencies include both the stylesheet and the files the stylesheet reads (e.g. tokens.ts). So if either changes, the importer is rebuilt.
  • A cycle from a stylesheet → an ordinary module → the same stylesheet is broken by a thread-local guard (Compiling). A stylesheet met again is read as unknown, so there is no infinite recursion.
  • Unchanged behavior:
    • A stylesheet that fails to extract, or an export that cannot be read as a literal, remains an error with a location, as before.
    • Declaring createThemeContract directly inside an ordinary module is still an error, as before.
  • Docs: in the "Ordinary modules" section (en/ko) of the vanilla-extract migration page, fixed the description that docs: align public examples with emitted output and default breakpoints #760 had narrowed.
    • It now says the two-file example (button.ts) works.
    • Lists the supported read targets and the cases that are still errors.

Overlap with open PRs

Test plan

  • cargo test -p extractor --tests -j 2: all pass
  • New tests in vanilla_extract_theme_import_tests.rs:
    • contract / createTheme tuple / createGlobalTheme / createVar / devup css() namespace / JSX prop / style([base, …]) composition. In each case, checks that the names read match the stylesheet's own output, that the import is kept, and that the dependency is recorded
    • Checks that the composed class matches the class the stylesheet exported
    • Checks that tokens.ts, which the stylesheet reads, is included in the importer's dependencies
    • Checks that a stylesheet that fails to extract keeps the /src/button.ts:3:23 location error
    • Checks that it still compiles in a cycle where the stylesheet imports the importer back
    • insta snapshot of the docs' button.ts example
  • stylesheet_exports unit test: None when re-entering a stylesheet that is being compiled
  • cargo clippy -p extractor --all-targets -- -D warnings, cargo fmt --all --check
  • prettier check on the docs and changepack

요약

DOC-09 후속 작업입니다. #760에서 "별도 PR로 지원하겠다"고 했던 내용입니다.

문제

  • 일반 모듈(.css.ts가 아닌 .ts/.tsx)이 theme.css.ts의 vars를 import해서 vars.space, vars.colors.bg 등을 style()/css()/JSX prop에서 읽으면 빌드 오류가 났습니다. 오류 메시지는 `css()` cannot use `vars.space` at build time 입니다.
  • theme.css.ts와 tokens.ts가 정상적으로 해석되는 경우에도 마찬가지였습니다.
  • main에서 테스트로 재현했습니다.

수정

  • imported-constants 리더(Modules::resolve_exports)가 import 대상이 vanilla-extract 스타일시트(.css.ts/.css.js)이면 그 파일을 번들러와 같은 방식으로 추출합니다(extract_with_source_map). 추출된 출력 코드에서 export를 리터럴로 읽습니다.
    • 새 파일: imported_constants/stylesheet_exports.rs
    • 이 경로로 읽는 것: createThemeContract/createTheme/createGlobalTheme의 vars 객체, 테마 클래스, createVar 변수, style 클래스 이름
    • 따라서 style({ margin: vars.space })는 스타일시트 자신의 CSS가 선언한 var(--space-…)와 같은 이름으로 컴파일됩니다.
    • style([base, …])도 스타일시트가 생성한 클래스를 그대로 유지합니다.
  • 스타일시트 import는 남겨서 그 CSS가 로드되게 했습니다.
  • 의존성에는 스타일시트와, 스타일시트가 읽는 파일(예: tokens.ts)을 모두 넣었습니다. 그래서 둘 중 하나가 바뀌면 importer가 다시 빌드됩니다.
  • 스타일시트 → 일반 모듈 → 같은 스타일시트로 이어지는 순환은 thread-local 가드(Compiling)로 끊습니다. 다시 만난 스타일시트는 unknown으로 읽혀 무한 재귀가 생기지 않습니다.
  • 바뀌지 않은 동작:
    • 추출에 실패하는 스타일시트나 리터럴로 읽을 수 없는 export는 기존처럼 위치가 표시된 오류로 남습니다.
    • 일반 모듈 안에서 직접 createThemeContract를 선언하는 경우도 기존처럼 오류입니다.
  • 문서: vanilla-extract 마이그레이션 페이지의 "Ordinary modules" 섹션(en/ko)에서 #760이 좁혀 둔 설명을 고쳤습니다.
    • 두 파일 예제(button.ts)가 이제 동작한다고 설명합니다.
    • 지원하는 읽기 대상과, 여전히 오류가 되는 경우를 적었습니다.

열려 있는 PR과의 겹침

테스트 계획

  • cargo test -p extractor --tests -j 2: 전체 통과
  • 새 테스트 vanilla_extract_theme_import_tests.rs:
    • contract / createTheme 튜플 / createGlobalTheme / createVar / devup css() 네임스페이스 / JSX prop / style([base, …]) 조합. 각 경우에 읽힌 이름이 스타일시트 자신의 출력과 같은지, import가 남는지, 의존성이 기록되는지 확인
    • 조합된 클래스가 스타일시트가 export한 클래스와 같은지 확인
    • 스타일시트가 읽는 tokens.ts가 importer 의존성에 포함되는지 확인
    • 추출에 실패하는 스타일시트는 /src/button.ts:3:23 위치 오류가 유지되는지 확인
    • 스타일시트가 importer를 다시 import하는 순환에서도 컴파일되는지 확인
    • 문서의 button.ts 예제 insta 스냅샷
  • stylesheet_exports 단위 테스트: 컴파일 중인 스타일시트 재진입 시 None
  • cargo clippy -p extractor --all-targets -- -D warnings, cargo fmt --all --check
  • 문서와 changepack에 prettier 검사

Refs #693

🤖 Generated with Claude Code

An ordinary module importing `vars` from `theme.css.ts` and reading
`vars.space` in `style()`, `css()` or a JSX prop was a build error. The
imported-constants reader now extracts an imported `.css.ts` / `.css.js`
the way the bundler extracts it and reads its exports from that output,
so theme vars objects, theme classes, createVar variables and style
class names become the literals the stylesheet's own CSS uses.

The stylesheet import stays so its CSS loads, the importer depends on
the stylesheet and the files it reads, a stylesheet reached again while
it is being compiled reads as unknown, and a stylesheet that fails to
extract keeps the located error. The migration guide documents the
supported reads.

Refs #693

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
libs/extractor/src/imported_constants.rs 100.00% <100.00%> (ø)
...actor/src/imported_constants/stylesheet_exports.rs 100.00% <100.00%> (ø)
libs/extractor/src/lib.rs 100.00% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@owjs3901
owjs3901 merged commit c92c3f7 into main Nov 17, 2026
27 checks passed
@owjs3901
owjs3901 deleted the fix/vanilla-extract-theme-imports branch November 17, 2026 02:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant