import { readFileSync } from 'node:fs' import { fileURLToPath, URL } from 'node:url' import react from '@vitejs/plugin-react' import { defineConfig } from 'vite' /** * Library build: `npm run build` → dist/. * * One ES module per source file (preserveModules), so apps only bundle the * components they import. Dependencies stay external. Types come from * `tsc -p tsconfig.lib.json`; tokens.css and styles.css are added by the * build script. */ const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')) as { version: string dependencies: Record peerDependencies?: Record } const external = [...Object.keys(pkg.dependencies), ...Object.keys(pkg.peerDependencies ?? {})] /** * Component modules use hooks, so React Server Components must treat them as * client code. Pure helpers (cn, applyPalette, style maps) stay unmarked so a * server component can still call them. */ function isClientModule(fileName: string) { return ( fileName.startsWith('components/') && !fileName.endsWith('.tokens.js') && !fileName.endsWith('.fixtures.js') ) } export default defineConfig({ define: { __TANSY_VERSION__: JSON.stringify(pkg.version), }, plugins: [react()], build: { outDir: 'dist', emptyOutDir: true, sourcemap: true, copyPublicDir: false, lib: { entry: fileURLToPath(new URL('./src/index.ts', import.meta.url)), formats: ['es'], }, rollupOptions: { external: (id) => external.some((dep) => id === dep || id.startsWith(`${dep}/`)) || id.startsWith('react/'), output: { preserveModules: true, preserveModulesRoot: 'src', entryFileNames: '[name].js', banner: (chunk) => (isClientModule(chunk.fileName) ? "'use client';" : ''), }, }, }, })