Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

18.2 KB
Raw Blame

Dashboard code splitting

Status: Draft — design finalized and questions settled 2026-11-02; nothing built yet Target: Spree 6.1 Depends on: 5.6-dashboard-typed-plugin-routes.md (route composition in the host build), 6.0-admin-spa.md Author: Damian Legawiec Last updated: 2026-11-02 Tracking: Linear V-3776 · GitHub spree/spree#15073

Summary

The admin dashboard and the seller panel each ship as one JavaScript file: 7.86 MB raw and 2.10 MB gzipped for the dashboard at 6.0.2, loaded in full before the login page renders. Nothing on the serving side requires this. The spree_dashboard gem's SPA controller serves every file under the build directory with immutable caching, and the Docker image runs the same Vite build the starter runs, so a build made of chunks is served without any server change. This plan splits the build at the route level with TanStack Router's automatic code splitting, makes the shared packages tree-shakeable so route chunks stay small, loads the three heaviest libraries (TipTap, CodeMirror, Recharts) only when a page mounts them, and makes the running app recover when a deploy removes the chunks it was built against. The first load becomes the shell plus the current page; every later page arrives as a cached, content-hashed chunk.

Key Decisions (do not deviate without discussion)

  • Splitting happens in the build, not in route files. Both Vite plugins (@spree/dashboard/vite, @spree/seller-dashboard/vite) pass autoCodeSplitting: true to the TanStack Router plugin. Route files in the shell, in hosts and in plugins stay as they are; no lazyRouteComponent or createLazyFileRoute rewrites. The default behaviour splits component, pendingComponent, errorComponent and notFoundComponent; loaders stay in the main bundle so intent preloading keeps working.
  • The serving layer does not change. Spree::Dashboard::SpaController, the dist_path configuration, the Dockerfile and the starter's vite.config.ts are untouched. Vite's assets/ chunks are content-hashed and immutable; index.html stays no-cache. A plan that needed a server change here would be the wrong plan.
  • The four dashboard packages declare sideEffects. @spree/dashboard-ui, @spree/dashboard-core, @spree/dashboard and @spree/seller-dashboard set "sideEffects" to the explicit list of modules that must run on import: stylesheets, the shells' bootstrap modules (admin: i18n-setup, api-client-setup, nav/*, search/*; seller: i18n, nav/*), the tables/* modules every list route imports for their defineTable call, and the register.ts(x) slot modules next to the promotion, price-list, setup-task and custom-field editors. Without the flag Rollup keeps every barrel export reachable from any importer, and a route chunk that imports one button drags in the editors. With a wrong list a registry bootstrap is silently dropped, so the list is verified by the end-to-end suite, which exercises the sidebar, the settings nav and the command palette.
  • Heavy libraries load inside their components. RichTextEditor, CodeEditor and the chart components in @spree/dashboard-ui load TipTap, CodeMirror and Recharts with a dynamic import behind React.lazy and show their existing skeletons while the chunk arrives. Consumers keep importing the components as they do today; the deep-import convention for the JSON preview and the code editor stays valid but is no longer required for splitting.
  • A stale chunk reloads the page, at most once a minute. After a deploy, a browser holding the previous index.html asks for chunk hashes that no longer exist and gets index.html back from the SPA fallback. Both shells (Dashboard, SellerDashboard) listen for Vite's vite:preloadError and reload, recording the time in session storage; a second failure within a minute is left to the router's error component instead of reloading again, so a genuinely broken build shows an error rather than looping, while a second deploy later in the same open tab still recovers. TanStack Router's lazy route components already reload once on a failed import; the listener covers dependency chunks loaded through modulepreload.
  • Hosts and plugins need no code changes. A host rebuilds and gets chunks; its committed routeTree.gen.ts shows no diff from splitting alone. A plugin's file routes are composed by the same generator and are split the same way. Registry routes (defineDashboardPlugin routes with a component) keep the React.lazy guidance in the routes guide.
  • Heavy libraries defer inside their components (decided 2026-11-02). Chosen over extending the deep-import convention, which would break every consumer's imports and still load TipTap with the first order page, and over route splitting alone, which puts TipTap in the chunks of the pages most sessions open first. Accepted trade-off: one extra round trip the first time an editor or chart mounts, hidden behind the existing skeleton.
  • CI reports bundle sizes first, then enforces a budget (decided 2026-11-02). The single-bundle regression this plan fixes went unnoticed for the whole 6.0 cycle because nobody measured. The report step lands with the first pull request; the entry chunk's budget is set from the post-split measurement with headroom. Accepted trade-off: a legitimate growth of the shell needs a reviewed bump of the number.
  • Links preload on intent (decided 2026-11-02). defaultPreload: 'intent' in both routers, so a hover or focus fetches the chunk before the click. The dashboard has no route loaders, so preloading costs chunk fetches and no API calls; some fetched chunks go unused. Preloading does run beforeLoad, so the one hook with a side effect (_authenticated/$storeId.tsx calling adminClient.setStore) skips when preload is true.
  • The seller panel ships the split in the same release (decided 2026-11-02). The two packages share a version and a design system, so two releases with different bundling semantics were rejected. The seller router gains the pending and error components it lacks today as part of the work.
  • This ships in a minor, not a patch. It changes the shape of every host's build output and the bundling semantics of the packages (sideEffects), which is behaviour hosts and plugin authors can observe. The group's packages version with Spree, so it lands with 6.1.0.

Design Details

Where the bytes are

Measured on 6.0.2, starter build at /dashboard/:

Output Raw Gzipped
assets/index-*.js (one file) 7.86 MB 2.10 MB
assets/index-*.css 603 KB 113 KB

Everything else in dist/ is flag SVGs, fonts and the favicon, served on demand already. The JavaScript is the whole problem.

The route tree has 108 route files in the shell. The three libraries that only some pages need and that dominate the bundle:

Library Used by Pages that mount it
TipTap (@tiptap/*) dashboard-ui/src/ui/rich-text-editor.tsx orders (notes), customers (internal note), products (new and edit), categories, collections, custom fields, policies, translations dialog, seller profile, media descriptions; seller panel orders and policies
CodeMirror (@codemirror/*) dashboard-ui/src/ui/code-editor.tsx (already a deep import) email template editor
Recharts dashboard-ui/src/ui/chart.tsx, and directly by dashboard/src/components/spree/reporting/report-view.tsx reporting

Route-level splitting

packages/dashboard/src/vite/index.ts and packages/seller-dashboard/src/vite/index.ts both build a virtual route config and hand it to TanStackRouterVite. Each gains:

return TanStackRouterVite({
  target: 'react',
  virtualRouteConfig,
  routesDirectory: shellRoutesDir,
  generatedRouteTree: ...,
  autoCodeSplitting: true,
})

The plugin rewrites each route file at build time into a stub that imports its component on demand; the generated route tree file is unchanged, so hosts see no diff in routeTree.gen.ts. Rollup then emits one chunk per route plus shared chunks for code two or more routes import. The default split groups are kept; codeSplittingOptions.splitBehavior is available later if a route needs its loader split too, but nothing today needs it.

createDashboardRouter already sets defaultPendingComponent, defaultPendingMs: 300 and defaultPendingMinMs: 400, which is what shows while a route chunk loads. createSellerRouter sets none of them and gets the same three options plus the defaultErrorComponent, so the seller panel behaves the same on a slow chunk.

Both routers also set defaultPreload: 'intent', so hovering or focusing a link starts fetching that route's chunk before the click. The dashboard fetches data through TanStack Query hooks in components rather than route loaders, so intent preloading costs a chunk fetch and nothing else. beforeLoad hooks do run during a preload; _authenticated/$storeId.tsx sets the active store there and returns early when preload is true, so hovering a link into another store does not repoint the shared client.

Tree-shaking the shared packages

All four packages are consumed as source through the host's Vite build and none declares sideEffects. Rollup therefore treats every module as possibly side-effectful and the @spree/dashboard-ui barrel keeps the editors, the charts and the JSON viewer reachable from any component that imports a button through it. The existing comment in dashboard-ui/src/index.ts works around this for two modules by asking consumers to deep-import; autoCodeSplitting on its own would move those modules into every route chunk that touches the barrel, not out of the critical path.

Each package declares the modules that must run on import and nothing else:

// packages/dashboard-ui/package.json
"sideEffects": ["**/*.css"]

// packages/dashboard-core/package.json: its settings pages bare-import their tables
"sideEffects": ["**/*.css", "./src/tables/*.{ts,tsx}"]

// packages/dashboard/package.json
"sideEffects": [
  "**/*.css",
  "./src/api-client-setup.ts",
  "./src/i18n-setup.ts",
  "./src/nav/*.{ts,tsx}",
  "./src/search/*.{ts,tsx}",
  "./src/tables/*.{ts,tsx}",
  "./src/components/spree/**/register.{ts,tsx}"
]

// packages/seller-dashboard/package.json
"sideEffects": [
  "**/*.css",
  "./src/i18n.ts",
  "./src/nav/*.{ts,tsx}",
  "./src/tables/*.{ts,tsx}"
]

The list is built from every bare import './x' in the three packages' src/ (the admin shell's are in dashboard.tsx, the seller panel's in index.ts, and some fifty route and page files bare-import a tables/* or register module) and from a grep for top-level registry calls outside those modules: nav.add, settingsNav.addGroup, searchRegistry.add, createActionRegistry.add, registerSlot, defineTable and i18n.addResourceBundle. Globs match .tsx as well as .ts: nav/enterprise-previews.tsx and search/default.tsx both register on import. A module that registers at import time and is not on the list disappears from the build; that is the failure mode the end-to-end suite catches, so the suite runs against the preview build (it already does, E2E_PREVIEW=1).

Loading the heavy libraries on demand

With splitting and tree-shaking in place, TipTap would still load the first time an operator opens an order, because the notes card renders RichTextEditor. The component itself defers the library:

// dashboard-ui/src/ui/rich-text-editor.tsx
const Editor = lazy(() => import('./rich-text-editor/editor'))

export function RichTextEditor(props: RichTextEditorProps) {
  return (
    <Suspense fallback={<RichTextEditorSkeleton />}>
      <Editor {...props} />
    </Suspense>
  )
}

The TipTap imports move into rich-text-editor/editor.tsx; the public component, its props and its skeleton stay where they are, so the fourteen consumers in the dashboard and seller panel and any plugin importing RichTextEditor do not change. The same shape applies to CodeEditor (CodeMirror) and to the chart components (Recharts); reporting/report-view.tsx imports Recharts primitives directly today and moves onto the lazy chart components in the same step, otherwise the reporting chunk keeps the library eagerly. The editor appears after one extra round trip the first time it is needed; the chunk is cached afterwards.

Recovering from a stale build

The sequence after a deploy: a tab opened before it holds index.html naming chunk orders-abc123.js; the new build has orders-def456.js; the SPA controller answers the request for the old name with index.html and Cache-Control: no-cache; the browser fails to execute HTML as a module.

Two mechanisms cover it:

  • TanStack Router's lazy route components catch the import error and reload the page once (the router keeps a session-storage marker so a persistently missing chunk shows the error component instead of looping).
  • For chunks Vite preloads itself, Dashboard and SellerDashboard register one listener:
window.addEventListener('vite:preloadError', (event) => {
  const last = Number(sessionStorage.getItem('spree:reloaded-for-chunk') ?? 0)
  if (Date.now() - last < 60_000) return
  sessionStorage.setItem('spree:reloaded-for-chunk', String(Date.now()))
  event.preventDefault()
  window.location.reload()
})

The flag records when the tab last reloaded and is honoured for a minute. It is deliberately not cleared on a successful route load: the shell route resolves after every reload, so clearing it there would reinstate the loop for a build that is genuinely broken. Nothing is needed on the Rails side: the fallback to index.html is what makes the reload land on the new build.

Measuring and holding the line

The Packages workflow builds the dashboard already. A step after the build prints the gzipped size of the entry chunk and of the largest chunk, and fails when the entry chunk exceeds a budget set from the post-split measurement with headroom. The number lives in one place (packages/dashboard-starter/package.json under a spree.bundleBudget key or a small script in scripts/), so raising it is a reviewed change rather than a drift.

What hosts and plugin authors see

  • A host's next build after upgrading emits many files under assets/. Deploys that copy dist/ copy a directory already; nothing changes. A host that serves the build from a CDN gets long-lived caching per chunk, as before.
  • Hosts that import the shell's components directly into their own pages get them split like any other route.
  • Plugin authors: file routes are split automatically. Registry routes still use React.lazy for the component, as the routes guide says. The deep-import note in dashboard-ui/src/index.ts becomes a recommendation rather than a requirement, and the comment says so.
  • Upgrade note for 6.1: no action; a routeTree.gen.ts diff appears only if routes changed for other reasons.

Migration Path

  1. Baseline and report. Record the 6.0.2 numbers above in the plan and add the size report step to the Packages workflow, reporting only. Lands first so every later pull request shows its effect.
  2. sideEffects on the four packages. Build the allowlists from the bare imports and the registry grep above (bootstrap modules, tables/*, register.ts(x)), declare them, run the end-to-end suite against the preview build. Measure.
  3. autoCodeSplitting and preloading. Set the flag in both Vite plugins, add defaultPreload: 'intent' to both routers and the pending and error components to the seller router, and make $storeId's beforeLoad skip setStore on preload. Confirm the starter's routeTree.gen.ts has no diff and the scaffolded-app job stays green on TypeScript 6 and 7. Measure.
  4. Lazy editors and charts. Move the TipTap, CodeMirror and Recharts imports behind React.lazy inside their dashboard-ui components, with the existing skeletons as fallbacks; switch reporting/report-view.tsx from direct Recharts imports to those components. Measure.
  5. Stale-chunk recovery. Add the vite:preloadError listener to both shells, with an end-to-end spec that serves a build, replaces it with a rebuilt one and navigates.
  6. Budget. Turn the report into a failing check with the post-split entry size plus headroom.
  7. Docs and changesets. Update the routes guide and the dashboard-ui barrel comment; one minor changeset across the four packages; a line in the 6.1 upgrade guide saying no action is needed.

Constraints on Current Work

  • Do not add new import-time registration outside the modules the sideEffects lists name: the bootstrap modules (admin i18n-setup, api-client-setup, nav/*, search/*; seller i18n, nav/*), a tables/* module, or a register.ts(x) module next to the editors it registers. A module that registers at import time anywhere else will be dropped by the build once sideEffects lands.
  • Do not import TipTap, CodeMirror or Recharts outside dashboard-ui's own component for that library. Use RichTextEditor, CodeEditor and the chart components; a page that imports the library directly pins it into its chunk, or into the main bundle today. reporting/report-view.tsx is the one existing exception and step 4 removes it.
  • Keep deep imports for code-editor and the JSON preview until step 4 lands; do not add them to the barrel.
  • New shell top-level routes still go into the virtual skeleton in both Vite plugins (unchanged from the typed plugin routes plan).

Open Questions

None. The four questions the draft raised (how the heavy libraries defer, whether CI enforces a budget, intent preloading, and the seller panel's timing) were settled on 2026-11-02 and are recorded under Key Decisions.

References

  • docs/plans/5.6-dashboard-typed-plugin-routes.md — route composition in the host build, the virtual skeleton both Vite plugins keep.
  • docs/plans/6.0-admin-spa.md — the dashboard's structure and constraints.
  • docs/developer/dashboard/customization/routes.mdx — "Keep them out of the main bundle" for registry routes.
  • spree/dashboard/app/controllers/spree/dashboard/spa_controller.rb — the serving contract: immutable assets/, index.html fallback with no-cache.
  • packages/dashboard-ui/src/index.ts — the deep-import note that this plan makes optional.
  • TanStack Router: autoCodeSplitting and codeSplittingOptions in @tanstack/router-plugin.
  • Vite: vite:preloadError for failed dynamic imports.