diff --git a/.changepacks/changepack_log_vanilla_extract_theme_imports.json b/.changepacks/changepack_log_vanilla_extract_theme_imports.json
new file mode 100644
index 000000000..8085c1d33
--- /dev/null
+++ b/.changepacks/changepack_log_vanilla_extract_theme_imports.json
@@ -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 `` 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"
+}
diff --git a/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.ko.mdx b/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.ko.mdx
index ec465a4f8..8adc6fcf8 100644
--- a/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.ko.mdx
+++ b/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.ko.mdx
@@ -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 (스타일시트 파일이 아님)
@@ -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 (스타일시트 파일이 아님)
@@ -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` 파일로 옮기면 의존성이 사라집니다.
diff --git a/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.mdx b/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.mdx
index c9d38a73e..b75270f72 100644
--- a/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.mdx
+++ b/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.mdx
@@ -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)
@@ -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)
@@ -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.
diff --git a/libs/extractor/src/imported_constants.rs b/libs/extractor/src/imported_constants.rs
index 552b41553..b14125962 100644
--- a/libs/extractor/src/imported_constants.rs
+++ b/libs/extractor/src/imported_constants.rs
@@ -53,6 +53,7 @@ mod safety_tests;
mod imported_css_root;
mod change_presence;
+mod stylesheet_exports;
#[derive(Clone, Debug)]
enum Constant {
@@ -734,6 +735,7 @@ fn inline_in<'a>(
option,
exports: FxHashMap::default(),
loading: Vec::new(),
+ read: BTreeSet::new(),
};
let mut symbols: FxHashMap = FxHashMap::default();
let copy_symbols: FxHashSet<_> = declarations
@@ -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;
@@ -1130,6 +1132,7 @@ impl<'p, 'a, 'r> ChangeCheck<'p, 'a, 'r> {
option,
exports: FxHashMap::default(),
loading: Vec::new(),
+ read: BTreeSet::new(),
}),
}
}
@@ -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 {
- self.modules.borrow().exports.keys().cloned().collect()
+ self.modules.borrow().files()
}
/// The paths in what `name` holds that the module hands on where the
@@ -1492,9 +1495,16 @@ struct Modules<'r> {
option: &'r ExtractOption,
exports: FxHashMap>>,
loading: Vec,
+ /// Files the stylesheets read for their exports read in turn
+ read: BTreeSet,
}
impl Modules<'_> {
+ /// Every file what the modules export was read from
+ fn files(&self) -> BTreeSet {
+ self.exports.keys().chain(&self.read).cloned().collect()
+ }
+
fn exports(
&mut self,
specifier: &str,
@@ -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)
diff --git a/libs/extractor/src/imported_constants/stylesheet_exports.rs b/libs/extractor/src/imported_constants/stylesheet_exports.rs
new file mode 100644
index 000000000..781a8dd29
--- /dev/null
+++ b/libs/extractor/src/imported_constants/stylesheet_exports.rs
@@ -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> = const { RefCell::new(Vec::new()) };
+}
+
+/// Marks `path` as being compiled until dropped
+struct Compiling;
+
+impl Compiling {
+ fn enter(path: &str) -> Option {
+ 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 {
+ 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());
+ }
+}
diff --git a/libs/extractor/src/imported_constants_package_boundary_tests.rs b/libs/extractor/src/imported_constants_package_boundary_tests.rs
index fdae724ce..18707e6d5 100644
--- a/libs/extractor/src/imported_constants_package_boundary_tests.rs
+++ b/libs/extractor/src/imported_constants_package_boundary_tests.rs
@@ -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);
diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs
index 71b38efe2..dd929d206 100644
--- a/libs/extractor/src/lib.rs
+++ b/libs/extractor/src/lib.rs
@@ -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;
diff --git a/libs/extractor/src/local_capture_coverage_tests.rs b/libs/extractor/src/local_capture_coverage_tests.rs
index 2c64bb3a9..a28894dba 100644
--- a/libs/extractor/src/local_capture_coverage_tests.rs
+++ b/libs/extractor/src/local_capture_coverage_tests.rs
@@ -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 {
@@ -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();
diff --git a/libs/extractor/src/snapshots/extractor__vanilla_extract_theme_import_tests__documented_ordinary_module_reading_a_stylesheet_compiles.snap b/libs/extractor/src/snapshots/extractor__vanilla_extract_theme_import_tests__documented_ordinary_module_reading_a_stylesheet_compiles.snap
new file mode 100644
index 000000000..11c9ba55d
--- /dev/null
+++ b/libs/extractor/src/snapshots/extractor__vanilla_extract_theme_import_tests__documented_ordinary_module_reading_a_stylesheet_compiles.snap
@@ -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";
diff --git a/libs/extractor/src/vanilla_extract_theme_import_tests.rs b/libs/extractor/src/vanilla_extract_theme_import_tests.rs
new file mode 100644
index 000000000..1e41e4360
--- /dev/null
+++ b/libs/extractor/src/vanilla_extract_theme_import_tests.rs
@@ -0,0 +1,293 @@
+//! An ordinary module reading what a vanilla-extract stylesheet exports.
+
+use crate::{ExtractOption, ExtractStyleValue, ImportAlias, ResolvedModule, extract_with_modules};
+use css::{class_map::reset_class_map, file_map::reset_file_map};
+use rstest::rstest;
+use serial_test::serial;
+
+const THEME: &str = "import { createGlobalTheme, createTheme, createThemeContract, createVar, style } from '@vanilla-extract/css';
+import { BRAND } from './tokens';
+export const vars = createThemeContract({ colors: { bg: null }, space: null });
+export const light = createTheme(vars, { colors: { bg: 'white' }, space: '8px' });
+export const [themeClass, tuple] = createTheme({ space: { md: '8px' } });
+export const global = createGlobalTheme(':root', { brand: BRAND });
+export const accent = createVar();
+export const base = style({ padding: 4 });
+";
+
+const BROKEN: &str = "import { createThemeContract } from '@vanilla-extract/css';
+export const vars = createThemeContract(undefined.space);
+";
+
+const CYCLE: &str = "import { createThemeContract } from '@vanilla-extract/css';
+import { SIZE } from './size';
+export const vars = createThemeContract({ space: null });
+export const size = SIZE;
+";
+
+fn option() -> ExtractOption {
+ ExtractOption {
+ import_aliases: std::collections::HashMap::from([(
+ "@vanilla-extract/css".to_string(),
+ ImportAlias::NamedToNamed,
+ )]),
+ ..ExtractOption::default()
+ }
+}
+
+fn resolver(specifier: &str, _: &str) -> Option {
+ let (path, code) = match specifier {
+ "./theme.css" => ("/src/theme.css.ts", THEME),
+ "./tokens" => ("/src/tokens.ts", "export const BRAND = 'blue';"),
+ "./broken.css" => ("/src/broken.css.ts", BROKEN),
+ "./cycle.css" => ("/src/cycle.css.ts", CYCLE),
+ "./size" => (
+ "/src/size.ts",
+ "import { vars } from './cycle.css';\nexport const SIZE = '4px';\nexport const read = () => vars;\n",
+ ),
+ _ => return None,
+ };
+ Some(ResolvedModule {
+ path: path.to_string(),
+ code: code.to_string(),
+ })
+}
+
+fn extract(filename: &str, code: &str) -> Result {
+ extract_with_modules(filename, code, option(), false, &resolver)
+ .map_err(|error| error.to_string())
+}
+
+fn statics(output: &crate::ExtractOutput) -> Vec<(String, String)> {
+ let mut statics: Vec<(String, String)> = output
+ .styles
+ .iter()
+ .filter_map(|style| match style {
+ ExtractStyleValue::Static(style) => {
+ Some((style.property().to_string(), style.value().to_string()))
+ }
+ _ => None,
+ })
+ .collect();
+ statics.sort();
+ statics
+}
+
+#[rstest]
+#[case::contract(
+ "import { style } from '@vanilla-extract/css';\nimport { vars } from './theme.css';\nexport const button = style({ margin: vars.space, color: vars.colors.bg });\n",
+ &[("color", "var(--colors-bg-0-0)"), ("margin", "var(--space-0-1)")]
+)]
+#[case::theme_tuple_global_theme_and_var(
+ "import { style } from '@vanilla-extract/css';\nimport { accent, global, tuple } from './theme.css';\nexport const button = style({ padding: tuple.space.md, color: global.brand, background: accent });\n",
+ &[("background", "var(--var-0-6)"), ("color", "var(--brand-0-5)"), ("padding", "var(--space-md-0-4)")]
+)]
+#[case::devup_css_through_a_namespace(
+ "import { css } from '@devup-ui/react';\nimport * as theme from './theme.css';\nexport const button = css({ p: theme.tuple.space.md });\n",
+ &[("padding", "var(--space-md-0-4)")]
+)]
+#[case::jsx_props(
+ "import { Box } from '@devup-ui/react';\nimport { vars } from './theme.css';\nexport const Button = () => ;\n",
+ &[("background", "var(--colors-bg-0-0)"), ("padding", "var(--space-0-1)")]
+)]
+#[case::composed_class(
+ "import { style } from '@vanilla-extract/css';\nimport { base } from './theme.css';\nexport const button = style([base, { color: 'red' }]);\n",
+ &[("color", "red")]
+)]
+#[serial]
+fn ordinary_module_reads_the_names_the_stylesheet_css_uses(
+ #[case] code: &str,
+ #[case] expected: &[(&str, &str)],
+) -> Result<(), String> {
+ // Given: the stylesheet extracted the way the bundler extracts it
+ reset_class_map();
+ reset_file_map();
+ let stylesheet = extract("/src/theme.css.ts", THEME)?;
+ // When
+ let output = extract("/src/button.tsx", code)?;
+ // Then: every name read is one the stylesheet itself exports
+ let expected: Vec<(String, String)> = expected
+ .iter()
+ .map(|(property, value)| ((*property).to_string(), (*value).to_string()))
+ .collect();
+ assert_eq!(statics(&output), expected);
+ for (_, value) in &expected {
+ assert!(
+ !value.starts_with("var(") || stylesheet.code.contains(value.as_str()),
+ "{value} is not in {}",
+ stylesheet.code
+ );
+ }
+ assert!(
+ output.code.contains("from \"./theme.css\""),
+ "{}",
+ output.code
+ );
+ assert!(
+ output
+ .dependencies
+ .iter()
+ .any(|file| file == "/src/theme.css.ts"),
+ "{:?}",
+ output.dependencies
+ );
+ Ok(())
+}
+
+#[test]
+#[serial]
+fn composed_class_is_the_one_the_stylesheet_exports() -> Result<(), String> {
+ // Given
+ reset_class_map();
+ reset_file_map();
+ let stylesheet = extract("/src/theme.css.ts", THEME)?;
+ let base = stylesheet
+ .code
+ .split("export const base = \"")
+ .nth(1)
+ .and_then(|rest| rest.split('"').next())
+ .ok_or_else(|| stylesheet.code.clone())?
+ .to_string();
+ // When
+ let output = extract(
+ "/src/button.ts",
+ "import { style } from '@vanilla-extract/css';\nimport { base } from './theme.css';\nexport const button = style([base, { color: 'red' }]);\n",
+ )?;
+ // Then
+ assert!(
+ output
+ .code
+ .contains(&format!("export const button = \"{base} ")),
+ "{}",
+ output.code
+ );
+ Ok(())
+}
+
+#[test]
+#[serial]
+fn importer_depends_on_what_the_stylesheet_reads() -> Result<(), String> {
+ // Given
+ reset_class_map();
+ reset_file_map();
+ // When
+ let output = extract(
+ "/src/button.ts",
+ "import { style } from '@vanilla-extract/css';\nimport { global } from './theme.css';\nexport const button = style({ color: global.brand });\n",
+ )?;
+ // Then
+ assert!(
+ output
+ .dependencies
+ .iter()
+ .any(|file| file == "/src/tokens.ts"),
+ "{:?}",
+ output.dependencies
+ );
+ Ok(())
+}
+
+#[test]
+#[serial]
+fn stylesheet_that_fails_stays_a_located_error() {
+ // Given
+ reset_class_map();
+ reset_file_map();
+ // When
+ let error = extract(
+ "/src/button.ts",
+ "import { style } from '@vanilla-extract/css';\nimport { vars } from './broken.css';\nexport const button = style({ margin: vars.space });\n",
+ );
+ // Then
+ assert_eq!(
+ error.err().as_deref(),
+ Some(
+ "/src/button.ts:3:23: `css()` cannot use `vars.space` at build time: its values must be literals, theme tokens or constants, or be computed from them"
+ )
+ );
+}
+
+#[test]
+#[serial]
+fn stylesheet_importing_its_importer_still_compiles() -> Result<(), String> {
+ // Given
+ reset_class_map();
+ reset_file_map();
+ // When
+ let output = extract(
+ "/src/size.tsx",
+ "import { css } from '@devup-ui/react';\nimport { vars, size } from './cycle.css';\nexport const box = css({ p: vars.space, m: size });\n",
+ )?;
+ // Then
+ assert_eq!(
+ statics(&output),
+ [
+ ("margin".to_string(), "4px".to_string()),
+ ("padding".to_string(), "var(--space-1-0)".to_string())
+ ]
+ );
+ Ok(())
+}
+
+const DOCUMENTED_THEME: &str =
+ "import { createTheme, createThemeContract, style } from '@vanilla-extract/css'
+
+export const vars = createThemeContract({ colors: { bg: null }, space: null })
+export const light = createTheme(vars, {
+ colors: { bg: 'white' },
+ space: '8px',
+})
+export const box = style({ background: vars.colors.bg })
+export const base = style({ padding: 8 })
+";
+
+fn documented(specifier: &str, _: &str) -> Option {
+ let (path, code) = match specifier {
+ "./theme.css" => ("/src/theme.css.ts", DOCUMENTED_THEME),
+ "./tokens" => ("/src/tokens.ts", "export const PRIMARY = 'blue'\n"),
+ _ => return None,
+ };
+ Some(ResolvedModule {
+ path: path.to_string(),
+ code: code.to_string(),
+ })
+}
+
+#[test]
+#[serial]
+fn documented_ordinary_module_reading_a_stylesheet_compiles() -> Result<(), String> {
+ // Given: the migration guide's `button.ts`
+ reset_class_map();
+ reset_file_map();
+ let option = ExtractOption {
+ import_main_css: false,
+ ..option()
+ };
+ extract_with_modules(
+ "/src/theme.css.ts",
+ DOCUMENTED_THEME,
+ option.clone(),
+ false,
+ &documented,
+ )
+ .map_err(|error| error.to_string())?;
+ // When
+ let output = extract_with_modules(
+ "/src/button.ts",
+ "import { style } from '@vanilla-extract/css'\n\nimport { base, vars } from './theme.css'\nimport { PRIMARY } from './tokens'\n\nexport const button = style([base, { color: PRIMARY, margin: vars.space }])\n",
+ option,
+ false,
+ &documented,
+ )
+ .map_err(|error| error.to_string())?;
+ // Then
+ insta::assert_snapshot!(output.code);
+ assert_eq!(
+ statics(&output),
+ [
+ ("color".to_string(), "blue".to_string()),
+ ("margin".to_string(), "var(--space-0-1)".to_string())
+ ]
+ );
+ Ok(())
+}