Skip to content

Commit 05e8700

Browse files
committed
build: publish one ES module per source file so apps can tree-shake
dist/index.js was one esbuild bundle. Bundling turns each export * as Menu into an object built at load time, so an app's bundler kept every component and the Base UI modules behind them: a Vite app that imported only Button grew by 331 kB (104 kB gzipped), and the web clipper's shared chunk by 198 kB. scripts/modules.mjs now builds each source file to its own module, with relative imports rewritten to .js files and 'use client' on each. The public API and the single entry point are unchanged. Importing only Button now adds 9 kB. test/modules.test.ts bundles a stand-in app and fails if importing Button or Menu and Tooltip pulls in other components.
1 parent 9e59c31 commit 05e8700

5 files changed

Lines changed: 123 additions & 12 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,8 @@ The tests enforce part of this: `inventory.test.ts` fails when a component folde
6262
- `src/styles/tokens.css`: every token, published as `@usememos/ui/tokens.css`
6363
- `src/styles/styles.css`: imports `foundation.css` (size rows, depth, focus, icons, type scale) and each component's stylesheet; published as one file, `@usememos/ui/styles.css`
6464
- `src/components/<name>/`: one folder per component, with its stylesheet
65-
- `scripts/build.mjs`: the build (esbuild, then `tsc` for the declarations, then `llms.txt` and `llms-full.txt` from `docs/` by `scripts/llms.mjs`)
66-
- `test/`: Vitest tests: tokens and docs in sync, color contrast, CSS rules, the inventory, component behavior
65+
- `scripts/build.mjs`: the build (the JavaScript by `scripts/modules.mjs`, the stylesheets by esbuild, then `tsc` for the declarations, then `llms.txt` and `llms-full.txt` from `docs/` by `scripts/llms.mjs`). The JavaScript ships as one ES module per source file, never one bundled file, so apps' bundlers drop the components they don't import
66+
- `test/`: Vitest tests: tokens and docs in sync, color contrast, CSS rules, the inventory, component behavior, and that an app importing one component bundles only that component
6767
- `playground/`: the test page. It renders every component section and the foundations, in the theme and size given by `?theme=` and `?size=`. The browser tests and screenshots run against its build. It is a test fixture, not a site for people to browse. `playground/interop.html` loads the components inside an app-like stylesheet (its own variables, a reset layer, utility classes, an app theme) for `e2e/interop.spec.ts`.
6868
- `e2e/`: Playwright browser tests
6969
- `docs/`: the design system docs. They also ship in the package as `llms.txt` and `llms-full.txt`, for agents in apps

‎packages/ui/scripts/build.mjs‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
// Builds the published package into dist/: an ES module, the stylesheets
1+
// Builds the published package into dist/: the ES modules, the stylesheets
22
// and type declarations. Run with `npm run build`.
33
import { execFileSync } from 'node:child_process';
44
import { copyFileSync, existsSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
55
import { dirname, join, resolve } from 'node:path';
66
import { fileURLToPath } from 'node:url';
77
import { build } from 'esbuild';
88
import { buildLlms } from './llms.mjs';
9+
import { buildModules } from './modules.mjs';
910

1011
const pkg = resolve(dirname(fileURLToPath(import.meta.url)), '..');
1112
const dist = join(pkg, 'dist');
@@ -17,15 +18,7 @@ rmSync(dist, { recursive: true, force: true });
1718
// readable stack traces. An app's bundler minifies them again either way.
1819
const shared = { bundle: true, format: 'esm', target: 'es2022', minify: true, sourcemap: true, logLevel: 'warning' };
1920

20-
await build({
21-
...shared,
22-
entryPoints: [src('index.ts')],
23-
outfile: join(dist, 'index.js'),
24-
jsx: 'automatic',
25-
// Components use hooks, so React Server Components must load them as client code.
26-
banner: { js: "'use client';" },
27-
external: ['react', 'react/*', 'react-dom', 'lucide-react', '@base-ui/react', '@base-ui/react/*'],
28-
});
21+
await buildModules(src('.'), dist);
2922

3023
// tokens.css and styles.css ship separately, so an app can load the tokens alone.
3124
// styles.css imports foundation.css and each component's stylesheet; esbuild

‎packages/ui/scripts/modules.d.mts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/** Builds every module in srcDir into outDir: one ES module per source file. */
2+
export function buildModules(srcDir: string, outDir: string): Promise<void>;

‎packages/ui/scripts/modules.mjs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Builds the package's JavaScript: one ES module per source file, so an app's
2+
// bundler drops the components it doesn't import. A single bundled file turns
3+
// each `export * as Menu` into an object built at load time, which keeps every
4+
// component in every app. Used by build.mjs and by test/modules.test.ts.
5+
import { existsSync, readdirSync } from 'node:fs';
6+
import { join } from 'node:path';
7+
import { build } from 'esbuild';
8+
9+
/** Builds every module in srcDir into outDir, minified, with source maps. */
10+
export async function buildModules(srcDir, outDir) {
11+
await build({
12+
entryPoints: sourceFiles(srcDir),
13+
outdir: outDir,
14+
outbase: srcDir,
15+
bundle: true,
16+
// Each file stays a file: packages and the package's own modules are imports, not inlined code.
17+
packages: 'external',
18+
plugins: [keepRelativeImports()],
19+
format: 'esm',
20+
target: 'es2022',
21+
jsx: 'automatic',
22+
// An app's bundler minifies again either way; the maps keep stack traces readable.
23+
minify: true,
24+
sourcemap: true,
25+
// Components use hooks, so React Server Components must load them as client code.
26+
banner: { js: "'use client';" },
27+
logLevel: 'warning',
28+
});
29+
}
30+
31+
/** The package's TypeScript modules, without declaration files. */
32+
function sourceFiles(dir) {
33+
return readdirSync(dir, { recursive: true, encoding: 'utf8' })
34+
.filter((name) => /\.tsx?$/.test(name) && !name.endsWith('.d.ts'))
35+
.map((name) => join(dir, name));
36+
}
37+
38+
/**
39+
* Leaves each relative import in place as an external module, rewritten to
40+
* the file it builds to (`./size` to `./size.js`, `../button` to
41+
* `../button/index.js`), so the output also loads under Node's ESM rules.
42+
*/
43+
function keepRelativeImports() {
44+
return {
45+
name: 'keep-relative-imports',
46+
setup(build) {
47+
build.onResolve({ filter: /^\.\.?\// }, ({ path, resolveDir, kind }) => {
48+
if (kind === 'entry-point') return undefined;
49+
const base = join(resolveDir, path);
50+
for (const ext of ['.ts', '.tsx']) if (existsSync(base + ext)) return { path: `${path}.js`, external: true };
51+
for (const ext of ['.ts', '.tsx']) if (existsSync(join(base, `index${ext}`))) return { path: `${path}/index.js`, external: true };
52+
throw new Error(`Can't resolve ${path} from ${resolveDir}`);
53+
});
54+
},
55+
};
56+
}

‎packages/ui/test/modules.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// The published JavaScript tree-shakes: an app that imports one component
2+
// gets that component, not the whole package (scripts/modules.mjs).
3+
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4+
import { tmpdir } from 'node:os';
5+
import { join, relative } from 'node:path';
6+
import { build } from 'esbuild';
7+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
8+
import { buildModules } from '../scripts/modules.mjs';
9+
10+
const pkg = join(__dirname, '..');
11+
let app = '';
12+
13+
/** Package files an app's bundle keeps when the app imports `names`. */
14+
async function bundledFiles(names: string[]) {
15+
const entry = join(app, `entry-${names.join('-')}.js`);
16+
writeFileSync(entry, `import { ${names.join(', ')} } from '@usememos/ui';\nconsole.log(${names.join(', ')});\n`);
17+
const result = await build({
18+
entryPoints: [entry],
19+
bundle: true,
20+
write: false,
21+
metafile: true,
22+
format: 'esm',
23+
external: ['react', 'react/*', 'react-dom', 'lucide-react', '@base-ui/react', '@base-ui/react/*'],
24+
logLevel: 'silent',
25+
});
26+
const output = Object.values(result.metafile.outputs)[0];
27+
const ui = join(app, 'node_modules/@usememos/ui/dist');
28+
const kept = Object.entries(output?.inputs ?? {}).filter(([, input]) => input.bytesInOutput > 0);
29+
return kept.map(([path]) => relative(ui, join(process.cwd(), path))).filter((path) => !path.startsWith('..'));
30+
}
31+
32+
describe('published modules', () => {
33+
beforeAll(async () => {
34+
// A stand-in app with the package installed: the built modules and the real package.json, whose sideEffects field matters.
35+
app = mkdtempSync(join(tmpdir(), 'mu-modules-'));
36+
const installed = join(app, 'node_modules/@usememos/ui');
37+
mkdirSync(installed, { recursive: true });
38+
await buildModules(join(pkg, 'src'), join(installed, 'dist'));
39+
cpSync(join(pkg, 'package.json'), join(installed, 'package.json'));
40+
});
41+
42+
afterAll(() => rmSync(app, { recursive: true, force: true }));
43+
44+
it('mark every module as client code for React Server Components', () => {
45+
const index = readFileSync(join(app, 'node_modules/@usememos/ui/dist/index.js'), 'utf8');
46+
expect(index.startsWith("'use client';")).toBe(true);
47+
});
48+
49+
it('keep only Button when an app imports Button', async () => {
50+
const files = await bundledFiles(['Button']);
51+
expect(files).toContain('components/button/index.js');
52+
expect(files.filter((path) => path.startsWith('components/') && !path.startsWith('components/button/'))).toEqual([]);
53+
});
54+
55+
it('keep only the components an app uses through compound parts', async () => {
56+
const files = await bundledFiles(['Menu', 'Tooltip']);
57+
const components = [...new Set(files.filter((path) => path.startsWith('components/')).map((path) => path.split('/')[1]))].sort();
58+
expect(components).toEqual(['menu', 'tooltip']);
59+
});
60+
});

0 commit comments

Comments
 (0)