|
1 | 1 | import assert from "node:assert"; |
| 2 | +import { fileURLToPath } from "node:url"; |
2 | 3 | import rsc from "@hiogawa/vite-rsc/plugin"; |
3 | 4 | import tailwindcss from "@tailwindcss/vite"; |
4 | 5 | import react from "@vitejs/plugin-react"; |
5 | | -import { defineConfig } from "vite"; |
| 6 | +import { type Rollup, defineConfig, normalizePath } from "vite"; |
6 | 7 | import Inspect from "vite-plugin-inspect"; |
7 | 8 |
|
8 | 9 | export default defineConfig({ |
@@ -100,6 +101,74 @@ export default { fetch: handler }; |
100 | 101 | } |
101 | 102 | }, |
102 | 103 | }, |
| 104 | + { |
| 105 | + name: "optimize-chunks", |
| 106 | + apply: "build", |
| 107 | + config() { |
| 108 | + const resolvePackageSource = (source: string) => |
| 109 | + normalizePath(fileURLToPath(import.meta.resolve(source))); |
| 110 | + |
| 111 | + const pkgBrowserPath = resolvePackageSource( |
| 112 | + "@hiogawa/vite-rsc/browser", |
| 113 | + ); |
| 114 | + |
| 115 | + // Non-functional form cannot handle commonjs plugin module |
| 116 | + // e.g. `(id)?commonjs-es-import` |
| 117 | + // manualChunks: { |
| 118 | + // "lib-react": [ |
| 119 | + // "react", |
| 120 | + // "react/jsx-runtime", |
| 121 | + // "react-dom/client", |
| 122 | + // "react-server-dom-webpack/client.browser", |
| 123 | + // ], |
| 124 | + // } |
| 125 | + |
| 126 | + const manualChunksFn: Rollup.ManualChunksOption = (id, meta) => { |
| 127 | + // users can merge client reference chunks by own heuristics |
| 128 | + if (id.startsWith("\0virtual:vite-rsc/build-client-reference/")) { |
| 129 | + const info = meta.getModuleInfo(id)!; |
| 130 | + const originalId = info.importedIds[0]!; |
| 131 | + // e.g. group by directory |
| 132 | + if (originalId.includes("/src/routes/chunks/")) { |
| 133 | + return "rsc-custom"; |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + // similar to |
| 138 | + // https://github.com/web-infra-dev/rsbuild/blob/main/packages/plugin-react/src/splitChunks.ts |
| 139 | + if ( |
| 140 | + id.includes("node_modules/react/") || |
| 141 | + id.includes("node_modules/react/") || |
| 142 | + id.includes("node_modules/react-dom/") || |
| 143 | + id.includes("node_modules/react-server-dom-webpack/") |
| 144 | + ) { |
| 145 | + return "lib-react"; |
| 146 | + } |
| 147 | + |
| 148 | + if ( |
| 149 | + id === "\0virtual:vite-rsc/entry-browser" || |
| 150 | + id === pkgBrowserPath |
| 151 | + ) { |
| 152 | + return "rsc-entry"; |
| 153 | + } |
| 154 | + }; |
| 155 | + |
| 156 | + return { |
| 157 | + environments: { |
| 158 | + client: { |
| 159 | + build: { |
| 160 | + manifest: true, |
| 161 | + rollupOptions: { |
| 162 | + output: { |
| 163 | + manualChunks: manualChunksFn, |
| 164 | + }, |
| 165 | + }, |
| 166 | + }, |
| 167 | + }, |
| 168 | + }, |
| 169 | + }; |
| 170 | + }, |
| 171 | + }, |
103 | 172 | ], |
104 | 173 | build: { |
105 | 174 | minify: false, |
|
0 commit comments