Skip to content

Optimize domain organization bundle size with tree-shaking #1410

@jasonkuhrt

Description

@jasonkuhrt

Problem

Currently, when using domain organization, all domain code is imported upfront in the generated client, which prevents tree-shaking of unused domains. This can lead to larger bundle sizes when only a subset of domains are actually used.

Current Implementation

In client.ts, we import all domains unconditionally:

import * as $$Domains from './domains/index.js'

const context = $$Utilities.pipe(
  $$Utilities.contextEmpty,
  ctx => $$Utilities.Extensions.addAndApplyMany(ctx, [TransportHttp, DocumentBuilder({ domains: $$Domains })]),
  // ...
)

This means even if a user only calls client.pokemon.findByName(), all domains (trainer, battle, being, etc.) are bundled.

Desired Behavior

Ideally, bundlers should be able to tree-shake unused domains so that only the domains actually accessed by user code are included in the final bundle.

Workaround

Users can mitigate this by being selective about which domains they configure in their graffle.config.ts. If you only need 5% of your API surface area, only create domains for those fields:

export default {
  methodsOrganization: {
    domains: {
      rules: [
        // Only define domains for the parts of your API you actually use
        { pattern: 'pokemonByName', path: 'pokemon', methodName: 'findByName' },
        { pattern: 'pokemons', path: 'pokemon', methodName: 'list' },
      ],
    },
  },
}

This keeps the generated code small from the start.

Potential Solutions

  1. Lazy imports: Import domain modules dynamically when first accessed
  2. Property proxy: Use a Proxy to detect which domains are accessed and only import those
  3. Build-time analysis: Analyze user code to determine which domains are used and generate a custom import list
  4. Manual imports: Let users import specific domain modules explicitly instead of passing all domains

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions