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
11 changes: 11 additions & 0 deletions .changepacks/changepack_log_mdx_compiled_output.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"changes": {
"bindings/devup-ui-wasm/package.json": "Patch",
"bindings/devup-ui-binding/package.json": "Patch",
"packages/vite-plugin/package.json": "Patch",
"packages/webpack-plugin/package.json": "Patch",
"packages/rsbuild-plugin/package.json": "Patch"
},
"note": "MDX documents are extracted after the MDX plugin compiles them: the engine reads an `.mdx` filename as the JavaScript module (with or without JSX) an MDX compiler makes of it instead of rejecting the extension, the Vite plugin extracts `.mdx` in a `post` transform, and the webpack and Rsbuild plugins in a `post` loader; Next.js with Turbopack and the Bun plugin still leave MDX untransformed",
"date": "2026-11-15T00:00:00.000Z"
}
1 change: 1 addition & 0 deletions apps/landing/src/app/(detail)/docs/limitations/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ A dynamic value such as `width` becomes a CSS variable set in `style`, so a comp
- A styled-components or Emotion style function may read the theme only as `theme.a.b` (or `theme.a[2]`). Calls, whole-theme reads and runtime keys are build errors.
- Inside `<ClassNames>`, `cx(getClass())` is a build error; put the result in a variable first, which then joins as a class.
- `withComponent` takes a tag name or a component written as a name or `a.b`. A target only the runtime knows, as `withComponent(make())`, is a build error: the styled component compiles to a plain function with no `withComponent`. Pass the target directly, or render with `as`.
- An `.mdx` file is extracted after your MDX plugin compiles it to JavaScript, never as raw MDX. The Vite (`@mdx-js/rollup`), webpack and Rsbuild (`@mdx-js/loader`, `@rsbuild/plugin-mdx`) plugins and Next.js with webpack (`@next/mdx`) run their MDX step in a later phase: Vite in a `post` transform, webpack and Rsbuild in a `post` loader. Next.js with Turbopack and the Bun plugin do not extract MDX yet. The scan that reserves class names before a build reads JavaScript and TypeScript modules only, so a document's own classes are named when it compiles. Put components that need Devup UI styles in a `.tsx` module and use them from the document.
- The plugins read `jsxImportSource` from the `tsconfig.json` (or `jsconfig.json`) in the working directory. Opt out with `importAliases: { '@emotion/react/jsx-runtime': false }`.
- The Bun plugin compiles `.ts`, `.tsx`, `.jsx` and `.mjs` files, but `.js` files only inside `@devup-ui` packages: Devup UI code in a `.js` file of your own project reaches the runtime placeholders. Use `.jsx`, `.tsx` or `.mjs` for it. A Bun runtime plugin must return the source of every file it matches, and Bun reads that source as an ES module, so matching `.js` files would break CommonJS ones.
- Code that only the runtime can compute — other globals, `Date`, `Math.random`, `new`, classes, async code — is never run by the build; on an element it stays a CSS variable, elsewhere it is a build error.
Expand Down
6 changes: 3 additions & 3 deletions libs/extractor/src/barrel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use oxc_ast::ast::{
};
use oxc_parser::{Parser, ParserReturn};
use oxc_semantic::{Semantic, SemanticBuilder};
use oxc_span::{GetSpan, SourceType};
use oxc_span::GetSpan;
use oxc_syntax::node::NodeId;
use oxc_syntax::symbol::SymbolId;
use rustc_hash::{FxHashMap, FxHashSet};
Expand Down Expand Up @@ -90,7 +90,7 @@ fn analyze(module: &ResolvedModule, package: &str) -> Exports {
return exports;
}
let allocator = Allocator::default();
let source_type = SourceType::from_path(&module.path).unwrap_or_default();
let source_type = crate::parsing::path_source_type(&module.path).unwrap_or_default();
let program = Parser::new(&allocator, &module.code, source_type)
.parse()
.program;
Expand Down Expand Up @@ -980,7 +980,7 @@ pub(crate) fn rewrite(
return Barreled::Unchanged;
}
let allocator = Allocator::default();
let source_type = SourceType::from_path(filename).unwrap_or_default();
let source_type = crate::parsing::path_source_type(filename).unwrap_or_default();
let ParserReturn {
program,
fatal_error,
Expand Down
2 changes: 1 addition & 1 deletion libs/extractor/src/dead_properties/calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub(super) fn collect(
let parsed = oxc_parser::Parser::new(
&allocator,
code,
oxc_span::SourceType::from_path(filename)
crate::parsing::path_source_type(filename)
.unwrap_or_else(|_| oxc_span::SourceType::ts())
.with_module(true),
)
Expand Down
23 changes: 16 additions & 7 deletions libs/extractor/src/imported_styled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use oxc_ast::ast::{
use oxc_ast::builder::AstBuilder;
use oxc_ast_visit::{Visit, VisitMut, walk};
use oxc_parser::{Parser, ParserReturn};
use oxc_span::{GetSpan, SourceType, Span};
use oxc_span::{GetSpan, Span};
use rustc_hash::{FxHashMap, FxHashSet};

use crate::css_prop::{CssProp, CssTakers};
Expand Down Expand Up @@ -245,7 +245,12 @@ impl<'a> Reader<'_, 'a> {
mut program,
fatal_error,
..
} = Parser::new(&sub, &transformed, SourceType::from_path(path).ok()?).parse();
} = Parser::new(
&sub,
&transformed,
crate::parsing::path_source_type(path).ok()?,
)
.parse();
if fatal_error {
return None;
}
Expand Down Expand Up @@ -325,8 +330,12 @@ impl<'a> Reader<'_, 'a> {
&self.option.import_aliases,
);
let allocator = Allocator::default();
let parsed =
Parser::new(&allocator, &transformed, SourceType::from_path(path).ok()?).parse();
let parsed = Parser::new(
&allocator,
&transformed,
crate::parsing::path_source_type(path).ok()?,
)
.parse();
if parsed.fatal_error {
return None;
}
Expand Down Expand Up @@ -833,7 +842,7 @@ mod tests {
let source = format!(
"import * as UI from './base'; import {{ Child }} from './base'; import {{ jsx }} from 'react/jsx-runtime'; {body}"
);
let parsed = Parser::new(&allocator, &source, SourceType::tsx()).parse();
let parsed = Parser::new(&allocator, &source, oxc_span::SourceType::tsx()).parse();
assert_eq!(parsed.diagnostics.len(), 0);
let scoping = oxc_semantic::SemanticBuilder::new()
.build(&parsed.program)
Expand Down Expand Up @@ -1778,7 +1787,7 @@ export default styled.span`margin: 1px;`;
fn exports_name_what_a_module_gives_other_files() {
let code = "import styled from '@emotion/styled';\nexport const A = 1, { b } = {};\nconst C = 2;\nexport { C, C as D };\nexport default C;\nexport function f() {}\nexport type { C as T };";
let allocator = Allocator::default();
let program = Parser::new(&allocator, code, SourceType::ts())
let program = Parser::new(&allocator, code, oxc_span::SourceType::ts())
.parse()
.program;
let exports = Exports::scan(&program);
Expand All @@ -1789,7 +1798,7 @@ export default styled.span`margin: 1px;`;
assert_eq!(exports.index("D"), 2);
assert!(!exports.has_anonymous_default());
let code = "export default styled.div`color: red;`;";
let program = Parser::new(&allocator, code, SourceType::ts())
let program = Parser::new(&allocator, code, oxc_span::SourceType::ts())
.parse()
.program;
let exports = Exports::scan(&program);
Expand Down
4 changes: 2 additions & 2 deletions libs/extractor/src/jsx_pragmas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use oxc_ast::{
ast::{Program, Statement},
};
use oxc_parser::Parser;
use oxc_span::{GetSpan, SourceType, Span};
use oxc_span::{GetSpan, Span};

/// The original header ends at the first body statement, not the first directive.
pub(crate) struct HeaderPragmas {
Expand Down Expand Up @@ -86,7 +86,7 @@ pub(crate) fn stylesheet_source(source: &str, generated: String, filename: &str)
let program = Parser::new(
&allocator,
source,
SourceType::from_path(filename).unwrap_or_default(),
crate::parsing::path_source_type(filename).unwrap_or_default(),
)
.parse()
.program;
Expand Down
3 changes: 2 additions & 1 deletion libs/extractor/src/module_reference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ pub fn original_module_references(
source: &str,
) -> HashMap<String, Vec<ModuleReferenceLocation>> {
let allocator = Allocator::default();
let source_type = SourceType::from_path(filename).unwrap_or_else(|_| SourceType::ts());
let source_type =
crate::parsing::path_source_type(filename).unwrap_or_else(|_| SourceType::ts());
let parsed = Parser::new(&allocator, source, source_type).parse();
let program = parsed.program;
let mut offsets = Vec::new();
Expand Down
64 changes: 62 additions & 2 deletions libs/extractor/src/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,25 @@ mod hybrid_tests;

/// Accept JavaScript JSX without changing the path's TypeScript or module dialect.
pub(super) fn source_type(filename: &str) -> Result<SourceType, UnknownExtension> {
SourceType::from_path(filename)
.map(|source_type| source_type.with_jsx(source_type.is_javascript()))
path_source_type(filename).map(|source_type| source_type.with_jsx(source_type.is_javascript()))
}

/// How the file at `path` parses, by its extension.
///
/// An `.mdx` file reaches the extractor as what an MDX compiler
/// (`@mdx-js/loader`, `@mdx-js/rollup`, `@next/mdx`) made of it: an ES
/// module of JavaScript that may keep JSX, never the MDX syntax itself.
pub(super) fn path_source_type(path: &str) -> Result<SourceType, UnknownExtension> {
if is_mdx(path) {
return Ok(SourceType::jsx());
}
SourceType::from_path(path)
}

fn is_mdx(path: &str) -> bool {
std::path::Path::new(path)
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("mdx"))
}

fn parse_physical<'a>(
Expand Down Expand Up @@ -203,6 +220,49 @@ mod tests {
assert!(has_devup_ui(filename, source, "@devup-ui/react"));
}

#[rstest]
#[case("docs/page.mdx")]
#[case("docs/PAGE.MDX")]
fn reads_mdx_as_compiled_javascript(#[case] filename: &str) {
// Given the path of an MDX file, which arrives already compiled.
// When its source type is taken from the path.
let actual = source_type(filename).unwrap();
// Then it parses as a JavaScript module that may keep JSX.
assert!(actual.is_javascript());
assert!(actual.is_module());
assert!(actual.is_jsx());
}

#[rstest]
#[case(
"docs/page.mdx",
"import {jsx as _jsx, jsxs as _jsxs} from 'react/jsx-runtime';\nimport { Box } from '@devup-ui/react';\nfunction _createMdxContent(props) {\n const _components = { h1: 'h1', ...props.components };\n return _jsxs(_components.h1, { children: ['Title', _jsx(Box, { bg: 'maroon', p: '13px', children: 'proof' })] });\n}\nexport default function MDXContent(props = {}) {\n return _createMdxContent(props);\n}"
)]
#[case(
"docs/page.mdx",
"import {jsxDEV as _jsxDEV} from 'react/jsx-dev-runtime';\nimport { Box } from '@devup-ui/react';\nexport default function MDXContent() {\n return _jsxDEV(Box, { bg: 'maroon', p: '13px', children: 'proof' }, undefined, false, undefined, this);\n}"
)]
#[case(
"docs/page.mdx",
"import { Box } from '@devup-ui/react';\nexport default function MDXContent() {\n return <><h1>Title</h1><Box bg=\"maroon\" p=\"13px\">proof</Box></>;\n}"
)]
#[serial]
fn extracts_compiled_mdx(#[case] filename: &str, #[case] source: &str) {
// Given what an MDX compiler makes of a document using Box: calls of
// the JSX runtime, or JSX kept with the `jsx` option.
reset_class_map();
reset_file_map();

// When the compiled module is extracted under its `.mdx` filename.
let output = extract(filename, source, ExtractOption::default()).unwrap();

// Then Box is compiled to a class like in any other module.
assert_eq!(output.styles.len(), 2, "{}", output.code);
assert!(!output.code.contains("Box"), "{}", output.code);
assert!(output.code.contains("className"), "{}", output.code);
assert!(has_devup_ui(filename, source, "@devup-ui/react"));
}

#[rstest]
#[case(
"import { Box } from '@devup-ui/react';\nconst view = <Box",
Expand Down
4 changes: 2 additions & 2 deletions libs/extractor/src/stylesheet_policy_dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub(crate) fn imports_plain(
resolver: Option<&ModuleResolver>,
) -> bool {
let allocator = Allocator::default();
let Ok(source_type) = SourceType::from_path(filename) else {
let Ok(source_type) = crate::parsing::path_source_type(filename) else {
return false;
};
let parsed = Parser::new(&allocator, code, source_type).parse();
Expand Down Expand Up @@ -93,7 +93,7 @@ impl<'s> Dispatch<'s> {

fn plan(&mut self, code: &str, filename: &str, is_static: &dyn Fn(&str) -> bool) -> Plan {
let allocator = Allocator::default();
let Ok(source_type) = SourceType::from_path(filename) else {
let Ok(source_type) = crate::parsing::path_source_type(filename) else {
return Plan::Run;
};
let parsed = Parser::new(&allocator, code, source_type).parse();
Expand Down
16 changes: 16 additions & 0 deletions packages/rsbuild-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,22 @@ describe('DevupUIRsbuildPlugin', () => {
getCssSpy.mockRestore()
}
})
it('extracts MDX in a post transform, after the MDX loader compiled it', async () => {
const transform = mock()
await DevupUI().setup(
createSetupContext({ transform, modifyRsbuildConfig: mock() }),
)
const source = transform.mock.calls.find(
([descriptor]) =>
String(descriptor.test) === String(/\.(tsx|ts|js|mjs|jsx)$/),
)
const mdx = transform.mock.calls.find(
([descriptor]) => descriptor.order === 'post',
)
expect(mdx?.[0]).toEqual({ test: /\.mdx$/i, order: 'post' })
expect(mdx?.[1]).toBe(source?.[1])
})

it('should transform code', async () => {
const plugin = DevupUI()
expect(plugin).toBeDefined()
Expand Down
Loading
Loading