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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ I needed a single source of truth for UI components that could drop into both li
## Features

- Traverses module graphs with a built-in walker to find transitive style imports (no bundler required).
- Resolution parity via [`oxc-resolver`](https://github.com/oxc-project/oxc-resolver): tsconfig `paths`, package `exports` conditions, and extension aliasing (e.g., `.css.js` → `.css.ts`) are honored without wiring up a bundler.
- Resolution parity via [`oxc-resolver`](https://github.com/oxc-project/oxc-resolver): tsconfig `paths`, package `exports` + `imports`, and extension aliasing (e.g., `.css.js` → `.css.ts`) are honored without wiring up a bundler.
- Compiles `*.css`, `*.scss`, `*.sass`, `*.less`, and `*.css.ts` (vanilla-extract) files out of the box.
- Optional post-processing via [`lightningcss`](https://github.com/parcel-bundler/lightningcss) for minification, prefixing, media query optimizations, or specificity boosts.
- Pluggable resolver/filter hooks for custom module resolution (e.g., Rspack/Vite/webpack aliases) or selective inclusion.
Expand Down Expand Up @@ -172,6 +172,9 @@ export async function render(url: string) {

The built-in walker already leans on [`oxc-resolver`](https://github.com/oxc-project/oxc-resolver), so tsconfig `paths`, package `exports` conditions, and common extension aliases work out of the box. If you still need to mirror bespoke behavior (virtual modules, framework-specific loaders, etc.), plug in a custom resolver. Here’s how to use [`enhanced-resolve`](https://github.com/webpack/enhanced-resolve):

> [!TIP]
> Hash-prefixed specifiers defined in `package.json#imports` resolve automatically—no extra loader or `css()` options required. Reach for a custom resolver only when you need behavior beyond what `oxc-resolver` already mirrors.

```ts
import { ResolverFactory } from 'enhanced-resolve'
import { css } from '@knighted/css'
Expand Down
3 changes: 3 additions & 0 deletions docs/loader.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ export default {
}
```

> [!NOTE]
> The loader shares the same auto-configured `oxc-resolver` as the standalone `css()` API, so hash-prefixed specifiers declared under `package.json#imports` (for example, `#ui/button`) resolve without additional options.

### Combined imports

Need the component exports **and** the compiled CSS from a single import? Use `?knighted-css&combined` and narrow the result with `KnightedCssCombinedModule` to keep TypeScript happy:
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/css/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@knighted/css",
"version": "1.0.0-rc.14",
"version": "1.0.0-rc.15",
"description": "A build-time utility that traverses JavaScript/TypeScript module dependency graphs to extract, compile, and optimize all imported CSS into a single, in-memory string.",
"type": "module",
"main": "./dist/css.js",
Expand Down
9 changes: 5 additions & 4 deletions packages/css/src/moduleGraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,10 @@ function normalizeSpecifier(raw: string): string {
if (!trimmed || trimmed.startsWith('\0')) {
return ''
}
const queryIndex = trimmed.search(/[?#]/)
const querySearchOffset = trimmed.startsWith('#') ? 1 : 0
const remainder = trimmed.slice(querySearchOffset)
const queryMatchIndex = remainder.search(/[?#]/)
const queryIndex = queryMatchIndex === -1 ? -1 : querySearchOffset + queryMatchIndex
const withoutQuery = queryIndex === -1 ? trimmed : trimmed.slice(0, queryIndex)
if (!withoutQuery) {
return ''
Expand Down Expand Up @@ -394,9 +397,7 @@ function createResolverFactory(
options.extensionAlias = extensionAlias
}
const tsconfigOption = resolveResolverTsconfig(graphOptions?.tsConfig, cwd)
if (tsconfigOption) {
options.tsconfig = tsconfigOption
}
options.tsconfig = tsconfigOption ?? 'auto'
return new ResolverFactory(options)
}

Expand Down
46 changes: 46 additions & 0 deletions packages/css/test/moduleGraph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,49 @@ import '@blocks/panel'
await project.cleanup()
}
})

test('collectStyleImports keeps hash-prefixed specifiers intact', async () => {
const project = await createProject('knighted-module-graph-imports-hash-')
try {
await project.writeFile(
'package.json',
JSON.stringify(
{
name: 'hash-imports',
type: 'module',
imports: {
'#ui/*': './src/ui/*',
},
},
null,
2,
),
)
await project.writeFile('src/ui/button.scss', '.button { color: hotpink; }')
await project.writeFile(
'src/ui/button.js',
`import './button.scss'
export const Button = () => null
`,
)
await project.writeFile(
'src/entry.ts',
`import { Button } from '#ui/button.js'
void Button
`,
)

const styles = await collectStyleImports(project.file('src/entry.ts'), {
cwd: project.root,
styleExtensions: ['.scss'],
filter: () => true,
})

assert.deepEqual(
await realpathAll(styles),
await realpathAll([project.file('src/ui/button.scss')]),
)
} finally {
await project.cleanup()
}
})
8 changes: 8 additions & 0 deletions packages/playwright/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# @knighted/css Playwright fixtures

This package builds the demo surface that Playwright pokes during CI. It now renders two scenarios side by side:

- **Lit + React wrapper**: the existing showcase that exercises vanilla CSS, Sass/Less, vanilla-extract, and the combined loader queries.
- **Hash-imports workspace demo**: a minimal npm workspace under `src/hash-imports-workspace/` where `apps/hash-import-demo` uses `package.json#imports` (hash-prefixed specifiers) to resolve UI modules provided by a sibling workspace package. The fixture proves that `@knighted/css/loader` and the standalone `css()` API honor `#workspace/*` specifiers with zero extra configuration.

Run `npm run test -- --project=chromium hash-imports.spec.ts` from this directory to rebuild the preview bundle and execute only the hash-imports checks. The default `npm test` target still runs the full matrix (chromium on CI plus the webpack + SSR builds).
2 changes: 1 addition & 1 deletion packages/playwright/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"pretest": "npm run build"
},
"dependencies": {
"@knighted/css": "1.0.0-rc.14",
"@knighted/css": "1.0.0-rc.15",
"@knighted/jsx": "^1.4.1",
"lit": "^3.2.1",
"react": "^19.0.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "@hash-imports/demo",
"private": true,
"type": "module",
"imports": {
"#workspace/ui/*": "./src/workspace-bridge/*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const HASH_IMPORTS_SECTION_ID = 'hash-imports-workspace'
export const HASH_IMPORTS_CARD_TEST_ID = 'hash-imports-card'
export const HASH_IMPORTS_BADGE_TEST_ID = 'hash-imports-badge'
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { HASH_IMPORTS_SECTION_ID } from '../../../constants.js'
import { createWorkspaceCard } from '#workspace/ui/workspace-card.js'
import { knightedCss as workspaceCardCss } from '#workspace/ui/workspace-card.js?knighted-css'

export function renderHashImportsWorkspaceDemo(root: HTMLElement): void {
const mount = root ?? document.body
const section = document.createElement('section')
section.dataset.testid = HASH_IMPORTS_SECTION_ID
section.className = 'hash-imports-workspace-section'
section.setAttribute('aria-label', 'Hash imports workspace fixture')

const intro = document.createElement('p')
intro.className = 'hash-imports-card__copy'
intro.textContent =
'#workspace/ui/* specifiers resolve automatically because the loader passes tsconfig: auto to oxc-resolver. The npm workspace wiring mirrors how downstream apps map UI packages via package.json#imports without custom resolver code.'

const style = document.createElement('style')
style.textContent = workspaceCardCss
section.append(style, intro, createWorkspaceCard())

mount.appendChild(section)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '../../../../packages/workspace-ui/src/workspace-card.js'
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../../../tsconfig.json",
"compilerOptions": {
"composite": true,
"rootDir": "./src",
"outDir": "./dist"
},
"include": ["src"]
}
3 changes: 3 additions & 0 deletions packages/playwright/src/hash-imports-workspace/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const HASH_IMPORTS_SECTION_ID = 'hash-imports-workspace'
export const HASH_IMPORTS_CARD_TEST_ID = 'hash-imports-card'
export const HASH_IMPORTS_BADGE_TEST_ID = 'hash-imports-badge'
9 changes: 9 additions & 0 deletions packages/playwright/src/hash-imports-workspace/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@hash-imports/workspace-root",
"private": true,
"type": "module",
"workspaces": [
"apps/*",
"packages/*"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "@hash-imports/workspace-ui",
"private": true,
"type": "module"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
.hash-imports-card {
background-image: linear-gradient(135deg, #fdf2f8 0%, #bfdbfe 60%, #d8b4fe 100%);
border: 2px solid #1d4ed8;
border-radius: 20px;
color: #0f172a;
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 1.75rem;
position: relative;
}

.hash-imports-card__badge {
align-self: flex-end;
background-color: #111827;
border-radius: 999px;
color: #fef9c3;
font-size: 0.7rem;
font-weight: 600;
letter-spacing: 0.08em;
padding: 0.25rem 0.85rem;
text-transform: uppercase;
}

.hash-imports-card__title {
font-size: 1.1rem;
font-weight: 600;
line-height: 1.3;
}

.hash-imports-card__description {
font-size: 0.95rem;
line-height: 1.5;
max-width: 46ch;
}

.hash-imports-card__copy {
color: #1e1b4b;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import './workspace-card.scss'

import {
HASH_IMPORTS_BADGE_TEST_ID,
HASH_IMPORTS_CARD_TEST_ID,
} from '../../../constants.js'

export type WorkspaceCardCopy = {
title: string
description: string
badge: string
}

export const workspaceCardCopy: WorkspaceCardCopy = {
title: 'Hash-prefixed imports stay zero-config',
description:
'This card renders with styles resolved via package.json#imports. The demo lives inside an npm workspace so the loader discovers tsconfig files and # specifiers without extra configuration.',
badge: 'workspace ready',
}

export function createWorkspaceCard(): HTMLElement {
const card = document.createElement('article')
card.className = 'hash-imports-card'
card.dataset.testid = HASH_IMPORTS_CARD_TEST_ID

const badge = document.createElement('span')
badge.className = 'hash-imports-card__badge'
badge.dataset.testid = HASH_IMPORTS_BADGE_TEST_ID
badge.textContent = workspaceCardCopy.badge

const title = document.createElement('h2')
title.className = 'hash-imports-card__title hash-imports-card__copy'
title.textContent = workspaceCardCopy.title

const description = document.createElement('p')
description.className = 'hash-imports-card__description hash-imports-card__copy'
description.textContent = workspaceCardCopy.description

card.append(badge, title, description)
return card
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../../../tsconfig.json",
"compilerOptions": {
"composite": true,
"rootDir": "./src",
"outDir": "./dist"
},
"include": ["src"]
}
7 changes: 7 additions & 0 deletions packages/playwright/src/hash-imports-workspace/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./apps/hash-import-demo/tsconfig.json" },
{ "path": "./packages/workspace-ui/tsconfig.json" }
]
}
2 changes: 2 additions & 0 deletions packages/playwright/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { renderLitReactDemo } from './lit-react/index.js'
import { renderHashImportsWorkspaceDemo } from './hash-imports-workspace/apps/hash-import-demo/src/render-hash-imports-demo.js'

function render() {
const root = document.getElementById('app') ?? document.body
renderLitReactDemo(root)
renderHashImportsWorkspaceDemo(root)
return root
}

Expand Down
47 changes: 47 additions & 0 deletions packages/playwright/test/hash-imports.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { expect, test } from '@playwright/test'

import {
HASH_IMPORTS_BADGE_TEST_ID,
HASH_IMPORTS_CARD_TEST_ID,
HASH_IMPORTS_SECTION_ID,
} from '../src/hash-imports-workspace/constants.js'

test.describe('hash imports workspace demo', () => {
test.beforeEach(async ({ page }) => {
page.on('console', msg => {
if (msg.type() === 'error') {
console.error(`[browser:${msg.type()}] ${msg.text()}`)
}
})
page.on('pageerror', error => {
console.error(`[pageerror] ${error.message}`)
})
await page.goto('/')
})

test('applies stylesheet resolved from # imports', async ({ page }) => {
const section = page.getByTestId(HASH_IMPORTS_SECTION_ID)
await expect(section).toBeVisible()

const card = page.getByTestId(HASH_IMPORTS_CARD_TEST_ID)
await expect(card).toBeVisible()

const metrics = await card.evaluate(node => {
const style = getComputedStyle(node as HTMLElement)
return {
backgroundImage: style.getPropertyValue('background-image').trim(),
borderColor: style.getPropertyValue('border-color').trim(),
}
})

expect(metrics.backgroundImage).toContain('linear-gradient')
expect(metrics.borderColor).toBe('rgb(29, 78, 216)')
})

test('badge copy references workspace context', async ({ page }) => {
const badge = page.getByTestId(HASH_IMPORTS_BADGE_TEST_ID)
await expect(badge).toBeVisible()
const text = await badge.textContent()
expect(text?.toLowerCase()).toContain('workspace')
})
})