Skip to content
Open
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
509 changes: 364 additions & 145 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@
"@figma/code-connect": "1.3.2",
"@primer/css": "^21.5.1",
"@primer/doc-gen": "^0.0.1",
"@tanstack/react-virtual": "^3.13.12",
"@rollup/plugin-babel": "6.1.0",
"@rollup/plugin-commonjs": "29.0.0",
"@rollup/plugin-json": "6.1.0",
Expand All @@ -119,6 +118,7 @@
"@storybook/addon-links": "^10.1.4",
"@storybook/icons": "^2.0.1",
"@storybook/react-vite": "^10.1.4",
"@tanstack/react-virtual": "^3.13.12",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.4.5",
"@testing-library/react": "^16.3.0",
Expand Down Expand Up @@ -170,8 +170,9 @@
"react-is": "18.3.1",
"recast": "0.23.7",
"rimraf": "5.0.5",
"rolldown": "^1.0.0-beta.53",
"rolldown-plugin-import-css": "^0.0.0",
"rollup": "4.53.3",
"rollup-plugin-import-css": "^0.0.0",
"storybook": "^10.1.4",
"terser": "5.36.0",
"ts-toolbelt": "9.6.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import path from 'node:path'
import commonjs from '@rollup/plugin-commonjs'
import resolve from '@rollup/plugin-node-resolve'
import babel from '@rollup/plugin-babel'
import {importCSS} from 'rollup-plugin-import-css'
import {defineConfig} from 'rolldown'
import {importCSS} from 'rolldown-plugin-import-css'
import postcssPresetPrimer from 'postcss-preset-primer'
import MagicString from 'magic-string'
import {isSupported} from './script/react-compiler.mjs'
import packageJson from './package.json' with {type: 'json'}

Expand Down Expand Up @@ -94,106 +92,11 @@ const baseConfig = {
],
],
}),
resolve({
extensions,
}),
commonjs({
extensions,
}),
importCSS({
modulesRoot: 'src',
postcssPlugins: [postcssPresetPrimer()],
postcssModulesOptions,
}),

/**
* This custom rollup plugin allows us to preserve directives in source
* code, such as "use client", in order to support React Server Components.
*
* The source for this plugin is inspired by:
* https://github.com/Ephem/rollup-plugin-preserve-directives
*/
{
name: 'preserve-directives',
transform(code) {
const ast = this.parse(code)
if (ast.type !== 'Program' || !ast.body) {
return {
code,
ast,
map: null,
}
}

let hasClientDirective = false

for (const node of ast.body) {
if (!node) {
continue
}

if (node.type !== 'ExpressionStatement') {
continue
}

if (node.directive === 'use client') {
hasClientDirective = true
break
}
}

if (hasClientDirective) {
return {
code,
ast,
map: null,
meta: {
hasClientDirective: true,
},
}
}

return {
code,
ast,
map: null,
}
},
renderChunk: {
order: 'post',
handler(code, chunk, options) {
// If `preserveModules` is not set to true, we can't be sure if the client
// directive corresponds to the whole chunk or just a part of it.
if (!options.preserveModules) {
return undefined
}

let chunkHasClientDirective = false

for (const moduleId of Object.keys(chunk.modules)) {
const hasClientDirective = this.getModuleInfo(moduleId)?.meta?.hasClientDirective
if (hasClientDirective) {
chunkHasClientDirective = true
break
}
}

if (chunkHasClientDirective) {
const transformed = new MagicString(code)
transformed.prepend(`"use client";\n`)
const sourcemap = transformed.generateMap({
includeContent: true,
})
return {
code: transformed.toString(),
map: sourcemap,
}
}

return null
},
},
},
],
onwarn(warning, defaultHandler) {
// Dependencies or modules may use "use client" as an indicator for React
Expand All @@ -210,17 +113,13 @@ const baseConfig = {
},
}

export default [
// ESM
{
...baseConfig,
external: dependencies.map(createPackageRegex),
output: {
interop: 'auto',
dir: 'dist',
format: 'esm',
preserveModules: true,
preserveModulesRoot: 'src',
},
export default defineConfig({
...baseConfig,
external: dependencies.map(createPackageRegex),
output: {
dir: 'dist',
format: 'esm',
preserveModules: true,
preserveModulesRoot: 'src',
},
]
})
2 changes: 1 addition & 1 deletion packages/react/script/build
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ npm run build:precompile-color-schemes
npm run type-css-modules

# Bundle
npx rollup -c
npx rolldown -c

# Type check
npx tsc --project tsconfig.build.json
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
# rollup-plugin-import-css
# rolldown-plugin-import-css

> A Rollup plugin to include generated CSS alongside transformed CSS Modules so
> A Rolldown plugin to include generated CSS alongside transformed CSS Modules so
> that importing a component from a library includes its CSS.

## Usage

```ts
// rollup.config.js
import {importCSS} from 'rollup-plugin-import-css'
// rolldown.config.js
import {importCSS} from 'rolldown-plugin-import-css'

export default {
input: ['src/index.ts'],
Expand Down
21 changes: 21 additions & 0 deletions packages/rolldown-plugin-import-css/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "rolldown-plugin-import-css",
"version": "0.0.0",
"private": true,
"type": "module",
"exports": "./src/index.ts",
"scripts": {
"type-check": "tsc --noEmit"
},
"peerDependencies": {
"postcss": "^8.4.38",
"postcss-modules": "^6.0.0"
},
"devDependencies": {
"postcss": "^8.4.38",
"postcss-modules": "^6.0.0",
"rolldown": "^1.0.0-beta.53",
"typescript": "^5.9.2"
},
"sideEffects": false
}
149 changes: 149 additions & 0 deletions packages/rolldown-plugin-import-css/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import type {Plugin} from 'rolldown'
import fs from 'node:fs/promises'
import path from 'node:path'
import {createHash} from 'node:crypto'
import postcss from 'postcss'
import postcssModules from 'postcss-modules'

interface ImportCSSOptions {
/**
* Provide the root directory for your package. This is used to calculate the
* relative path for generated CSS files
*/
modulesRoot: string

/**
* Optionally provide an array of postcss plugins to use during CSS
* compilation.
*/
postcssPlugins?: Array<postcss.AcceptedPlugin>

/**
* Optionally provide options to pass forward to `postcss-modules` when
* compiling CSS
*/
postcssModulesOptions?: Parameters<typeof postcssModules>[0]
}

export function importCSS(options: ImportCSSOptions): Plugin {
const {modulesRoot, postcssPlugins = [], postcssModulesOptions = {}} = options
const rootDirectory = path.isAbsolute(modulesRoot) ? modulesRoot : path.resolve(process.cwd(), modulesRoot)

return {
name: 'import-css',
resolveId: {
filter: {
id: /\.css$/,
},
handler(source, importer) {
if (!importer) {
return
}

const moduleInfo = this.getModuleInfo(importer)
if (moduleInfo?.meta['import-css']?.source === source) {
return {
id: source,
external: true,
moduleSideEffects: true,
}
}

const id = path.resolve(path.dirname(importer), source)
return path.format({
dir: path.dirname(id),
base: `${path.basename(id)}.js`,
})
},
},
load: {
filter: {
id: /\.css\.js$/,
},
handler() {
return ''
},
},
transform: {
filter: {
id: /\.module\.css\.js$/,
},
async handler(_code, id) {
const sourceId = path.join(path.dirname(id), path.basename(id, '.js'))
const code = await fs.readFile(sourceId, 'utf8')
const hash = getSourceHash(code)
const relativePath = path.relative(rootDirectory, sourceId)
const name = path.basename(relativePath, relativePath.endsWith('.module.css') ? '.module.css' : '.css')
const fileName = path.join(
path.dirname(relativePath),
path.format({
name: `${name}-${hash}`,
ext: '.css',
}),
)

// When transforming CSS modules, we want to emit the generated CSS as an
// asset and include the generated file in our generated CSS Modules file
// which contains the classes. This makes sure that if the file containing
// the classes is used, then the associated styles for those classes is
// also included

let cssModuleClasses: {[name: string]: string} | null = null
const result = await postcss([
...postcssPlugins,
postcssModules({
...postcssModulesOptions,
getJSON(filename, json) {
if (postcssModulesOptions.getJSON) {
postcssModulesOptions.getJSON(filename, json)
}
cssModuleClasses = json
},
}),
]).process(code, {
from: id,
to: fileName,
map: {
inline: false,
},
})

this.emitFile({
type: 'asset',
source: result.css,
fileName,
})
this.emitFile({
type: 'asset',
source: result.map.toString(),
fileName: `${fileName}.map`,
})

const moduleInfo = this.getModuleInfo(id)
const cssSource = `./${path.basename(fileName)}`
if (moduleInfo) {
moduleInfo.meta['import-css'] = {
source: cssSource,
}
}

return {
code: `
import '${cssSource}';
${
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
cssModuleClasses !== null ? `export default ${JSON.stringify(cssModuleClasses)}` : ''
}
`,
moduleSideEffects: 'no-treeshake',
}
},
},
}
}

const DEFAULT_HASH_SIZE = 8

function getSourceHash(source: string) {
return createHash('sha256').update(source).digest('hex').slice(0, DEFAULT_HASH_SIZE)
}
Loading
Loading