Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"changes": {
"bindings/devup-ui-wasm/package.json": "Patch"
},
"note": "An ordinary module (not .css.ts / .css.js) can now read what a vanilla-extract stylesheet exports: the vars objects of createThemeContract, createTheme and createGlobalTheme, theme classes, createVar variables and style class names. The imported stylesheet is extracted the way the bundler extracts it, so `style({ margin: vars.space })` or `<Box p={vars.space} />` compiles to the custom property the stylesheet's own CSS declares and `style([base, ...])` keeps the stylesheet's class. The import of the stylesheet stays so its CSS loads, and the importer depends on the stylesheet and the files it reads. A stylesheet that fails to extract, or an export the build cannot read as a literal, is still a located error",
"date": "2026-11-15T00:00:00.000Z"
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export const button = "b c";

`button`에는 충돌하는 red 클래스가 포함되지 않습니다. 빌드 시점에 알 수 없는 외부 클래스는 여전히 CSS 캐스케이드를 따르며, 클래스 이름 문자열의 순서가 덮어쓰기 규칙이 되지는 않습니다.

일반 모듈 추출은 생성된 커스텀 속성을 알아내기 위해 vanilla-extract 테마 계약을 실행하지 **않습니다**. 계약과 이를 사용하는 스타일은 `.css.ts` / `.css.js`에 함께 두세요. 예를 들어 이 페이지 상단의 스타일시트 예제를 일반 `theme.ts` 모듈로 저장하면 유효하지 않습니다:
일반 모듈 추출은 생성된 커스텀 속성을 알아내기 위해 그 모듈에 선언된 vanilla-extract 테마 계약을 실행하지 **않습니다**. 계약과 테마는 `.css.ts` / `.css.js`에 선언하세요. 예를 들어 이 페이지 상단의 스타일시트 예제를 일반 `theme.ts` 모듈로 저장하면 유효하지 않습니다:

```ts
// theme.ts (스타일시트 파일이 아님)
Expand All @@ -121,7 +121,7 @@ export const box = style({ background: vars.colors.bg })
`css()` cannot use `vars.colors.bg` at build time: its values must be literals, theme tokens or constants, or be computed from them
```

마찬가지로 위의 두 파일 스타일시트 예제도 같은 import가 일반 `.ts` 모듈에서 동작한다고 보장하지 않습니다:
하지만 일반 모듈은 스타일시트가 내보내는 값을 import할 수 있습니다. 빌드는 import된 `.css.ts` / `.css.js`를 번들러가 추출하는 방식 그대로 추출하고, 그 export를 스타일시트 자신의 CSS가 쓰는 리터럴로 읽습니다: `createThemeContract`, `createTheme`, `createGlobalTheme`의 vars 객체, 테마 클래스, `createVar` 변수, `style` 클래스 이름이 여기에 해당합니다. 따라서 위의 두 파일 예제는 일반 모듈에서도 동작합니다:

```ts
// button.ts (스타일시트 파일이 아님)
Expand All @@ -133,14 +133,14 @@ import { PRIMARY } from './tokens'
export const button = style([base, { color: PRIMARY, margin: vars.space }])
```

`theme.css.ts`와 `tokens.ts`를 해석할 수 있더라도, 이 예제를 빌드하면 7번째 줄 23번째 열의 테마 변수 읽기 위치와 함께 다음 메시지가 보고됩니다:
`vars.space`는 `theme.css.ts`가 선언한 커스텀 속성(`margin: var(--space-…)`)으로 읽히고, `base`는 `theme.css.ts`가 생성한 클래스를 그대로 더합니다. `./theme.css` import는 남으므로 그 CSS가 로드되며, 이 파일이나 이 파일이 읽는 파일이 바뀌면 `button.ts`가 다시 빌드됩니다.

이렇게 읽히는 것은 스타일시트의 export뿐입니다. 추출 중 예외를 던지는 스타일시트나, 빌드가 리터럴로 읽을 수 없는 export를 읽으면 여전히 위치가 표시된 오류가 보고됩니다:

```text
`css()` cannot use `vars.space` at build time: its values must be literals, theme tokens or constants, or be computed from them
```

이 모듈을 `button.css.ts`로 옮기고, 스타일과 테마 값은 유효한 스타일시트 모듈에서 내보내세요. 일반 모듈은 해석할 수 있는 리터럴 상수를 읽을 수 있지만, 그렇다고 생성된 테마 객체가 일반 리터럴 상수가 되는 것은 아닙니다. 빌드 시점에 알 수 있는 조합과, 일반 모듈 경로에서 해석할 수 없는 테마 변수 읽기를 혼동하지 마세요.

나머지 API는 스타일시트 파일 밖에서 `@vanilla-extract/css` import로 그대로 남습니다. 예를 들어 `createVar()`와 `styleVariants()`는 같은 모듈의 `style()` 호출이 변환되더라도 해당 패키지에 대한 호출로 남으며, 일반 모듈 추출 경로에서 평가되지 않습니다.

이 호출들을 vanilla-extract가 원래 권장하는 위치인 `.css.ts` 파일로 옮기면 의존성이 사라집니다.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,10 @@ Generated CSS:
still follow the CSS cascade; class-name string order is not an override rule.

Ordinary-module extraction does **not** execute a vanilla-extract theme contract
to discover its generated custom properties. Keep contracts and their consuming
styles together in `.css.ts` / `.css.js`. For example, the stylesheet example
at the top of this page is not valid if saved as an ordinary `theme.ts` module:
declared in that module to discover its generated custom properties. Declare
contracts and themes in `.css.ts` / `.css.js`. For example, the stylesheet
example at the top of this page is not valid if saved as an ordinary `theme.ts`
module:

```ts
// theme.ts (not a stylesheet file)
Expand All @@ -131,8 +132,12 @@ The probe locates the call at line 6, column 20 and reports this message:
`css()` cannot use `vars.colors.bg` at build time: its values must be literals, theme tokens or constants, or be computed from them
```

The two-file stylesheet example above likewise does not promise that the same
imports work in an ordinary `.ts` module:
An ordinary module can import what a stylesheet exports, though. The build
extracts the imported `.css.ts` / `.css.js` the way the bundler extracts it and
reads its exports as the literals its own CSS uses: the vars objects of
`createThemeContract`, `createTheme` and `createGlobalTheme`, theme classes,
`createVar` variables and `style` class names. So the two-file example above
also works as an ordinary module:

```ts
// button.ts (not a stylesheet file)
Expand All @@ -144,19 +149,19 @@ import { PRIMARY } from './tokens'
export const button = style([base, { color: PRIMARY, margin: vars.space }])
```

Even when `theme.css.ts` and `tokens.ts` resolve, the probe locates the
theme-variable read at line 7, column 23 and reports:
`vars.space` reads as the custom property `theme.css.ts` declares,
`margin: var(--space-…)`, and `base` contributes the class `theme.css.ts`
generates. The import of `./theme.css` stays, so its CSS is loaded, and a
change to it — or to a file it reads — rebuilds `button.ts`.

Only the stylesheet's exports are read this way. A stylesheet that throws while
it is extracted, or an export the build cannot read as a literal, still
reports the read as a located error:

```text
`css()` cannot use `vars.space` at build time: its values must be literals, theme tokens or constants, or be computed from them
```

Move that consuming module to `button.css.ts` and export the styles and theme
values from valid stylesheet modules. Ordinary modules can read resolvable
literal constants, but that does not make a generated theme object an ordinary
literal constant. A build-time-known composition must not be confused with a
theme-variable read the ordinary-module path cannot resolve.

The remaining APIs stay imported from `@vanilla-extract/css` outside a
stylesheet file. For example, `createVar()` and `styleVariants()` remain calls
to that package even when a `style()` call in the same module is transformed.
Expand Down
28 changes: 25 additions & 3 deletions libs/extractor/src/imported_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ mod safety_tests;
mod imported_css_root;

mod change_presence;
mod stylesheet_exports;

#[derive(Clone, Debug)]
enum Constant {
Expand Down Expand Up @@ -734,6 +735,7 @@ fn inline_in<'a>(
option,
exports: FxHashMap::default(),
loading: Vec::new(),
read: BTreeSet::new(),
};
let mut symbols: FxHashMap<SymbolId, Constant> = FxHashMap::default();
let copy_symbols: FxHashSet<_> = declarations
Expand Down Expand Up @@ -993,7 +995,7 @@ fn inline_in<'a>(
.visit_program(program);
reads_math
};
inlined.dependencies = modules.exports.into_keys().collect();
inlined.dependencies = modules.files();
let callbacks = bound_style_callbacks::rewrite(ast_builder, program, scoping, &option.package);
inlined.errors.extend(callbacks.errors);
let mut captures = callbacks.captures;
Expand Down Expand Up @@ -1130,6 +1132,7 @@ impl<'p, 'a, 'r> ChangeCheck<'p, 'a, 'r> {
option,
exports: FxHashMap::default(),
loading: Vec::new(),
read: BTreeSet::new(),
}),
}
}
Expand All @@ -1146,7 +1149,7 @@ impl<'p, 'a, 'r> ChangeCheck<'p, 'a, 'r> {

/// The modules read for the values of imports
pub(crate) fn dependencies(&self) -> BTreeSet<String> {
self.modules.borrow().exports.keys().cloned().collect()
self.modules.borrow().files()
}

/// The paths in what `name` holds that the module hands on where the
Expand Down Expand Up @@ -1492,9 +1495,16 @@ struct Modules<'r> {
option: &'r ExtractOption,
exports: FxHashMap<String, Rc<FxHashMap<String, Constant>>>,
loading: Vec<String>,
/// Files the stylesheets read for their exports read in turn
read: BTreeSet<String>,
}

impl Modules<'_> {
/// Every file what the modules export was read from
fn files(&self) -> BTreeSet<String> {
self.exports.keys().chain(&self.read).cloned().collect()
}

fn exports(
&mut self,
specifier: &str,
Expand All @@ -1519,7 +1529,19 @@ impl Modules<'_> {
return Err(ChainReason::Cycle);
}
self.loading.push(module.path.clone());
let exports = Rc::new(self.read(&module.path, &module.code));
let code = match stylesheet_exports::compiled(
&module.path,
&module.code,
self.option,
self.resolver,
) {
Some(output) => {
self.read.extend(output.dependencies);
output.code
}
None => module.code,
};
let exports = Rc::new(self.read(&module.path, &code));
self.loading.pop();
self.exports.insert(module.path, exports.clone());
Ok(exports)
Expand Down
71 changes: 71 additions & 0 deletions libs/extractor/src/imported_constants/stylesheet_exports.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//! What a vanilla-extract stylesheet exports, read the way the bundler
//! extracts it: its theme objects, theme classes and class names become the
//! literals its own CSS uses.

use std::cell::RefCell;

use crate::{ExtractOption, ExtractOutput, ModuleResolver, utils::is_vanilla_extract_file};

thread_local! {
/// Stylesheets being extracted for an importer, so one importing itself
/// through other modules reads as unknown instead of recursing
static COMPILING: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}

/// Marks `path` as being compiled until dropped
struct Compiling;

impl Compiling {
fn enter(path: &str) -> Option<Self> {
COMPILING.with_borrow_mut(|stack| {
(!stack.iter().any(|entry| entry == path)).then(|| {
stack.push(path.to_string());
Self
})
})
}
}

impl Drop for Compiling {
fn drop(&mut self) {
COMPILING.with_borrow_mut(Vec::pop);
}
}

/// The stylesheet at `path` extracted, when it is one and its extraction
/// succeeds: its code exports what the stylesheet's own CSS uses
pub(super) fn compiled(
path: &str,
code: &str,
option: &ExtractOption,
resolver: Option<&ModuleResolver>,
) -> Option<ExtractOutput> {
if !is_vanilla_extract_file(path) {
return None;
}
let _compiling = Compiling::enter(path)?;
crate::extract_with_source_map(path, code, option.clone(), false, resolver).ok()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn stylesheet_being_compiled_reads_as_unknown_until_it_ends() {
// Given
let outer = Compiling::enter("/src/a.css.ts");
// When
let inner = compiled(
"/src/a.css.ts",
"export const a = 1;",
&ExtractOption::default(),
None,
);
// Then
assert!(outer.is_some());
assert!(inner.is_none());
drop(outer);
assert!(Compiling::enter("/src/a.css.ts").is_some());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ fn package_boundary_css_styles_only_reads_api_exports(
option: &option,
exports: Default::default(),
loading: vec![],
read: Default::default(),
};
// When
let styles = scope.css_styles(&mut modules, call);
Expand Down
2 changes: 2 additions & 0 deletions libs/extractor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,8 @@ mod utf16_boundary_tests;
mod util_type;
mod utils;
mod vanilla_extract;
#[cfg(test)]
mod vanilla_extract_theme_import_tests;
mod visit;

mod dead_properties;
Expand Down
2 changes: 2 additions & 0 deletions libs/extractor/src/local_capture_coverage_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,7 @@ fn exact_array_spreads_keep_element_order_and_empty_spreads(
option: &option,
exports: FxHashMap::default(),
loading: vec![],
read: Default::default(),
};

let Some(Constant::Array(values)) = scope.evaluate(&mut modules, &statement.expression) else {
Expand Down Expand Up @@ -480,6 +481,7 @@ fn referenced_local_shapes_reject_eager_tdz_and_keep_safe_controls(
option: &option,
exports: FxHashMap::default(),
loading: vec![],
read: Default::default(),
};
let mut found = Vec::new();
let mut shapes = FxHashMap::default();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
source: libs/extractor/src/vanilla_extract_theme_import_tests.rs
expression: output.code
---
import "@devup-ui/react/devup-ui-1.css";
import { base, vars } from "./theme.css";
import { PRIMARY } from "./tokens";
export const button = "a-a b-a b-b";
Loading
Loading