Skip to content

Asset compiler pipeline (TS/Sass/esbuild) + static export #10

Open

Description

@JuroOravec

Design doc: docs/design/source_languages.md is the umbrella design for source-language declaration (*_lang attributes), the pluggable compiler registry, and when compilation runs. Read section 3.3 before building: it reframes the build-time / static-export model below as an open question and concludes that a django-style collectcomponent export is likely not a citry feature (lazy per-file compile plus a content-hash cache is the more probable direction).

Summary

A per-component asset compiler pipeline: map a component's co-located or inline JS/CSS to a
compiler by file type (esbuild/tsc for js/ts/jsx/tsx, an esbuild + sass plugin for
scss/sass, later Less/Stylus/Markdown/Pug), run them at build time, and write the results to a
static directory so production serves pre-built, hashed, code-split assets instead of inlining raw
source at render time.

This is planned as a core feature, not an extension. It defines the js_lang / css_lang
source-language contract and the static-export model that the built-in dependencies extension then
consumes, and it touches the render pipeline (Markdown/Pug run right after a template renders). It is
also the prerequisite substrate for several would-be extensions (Tailwind, a SASS/TS workflow, a
minifier), so it belongs below the extension layer.

It was prototyped in the old django-components workspace and left unfinished. This issue records that
prototype in depth so the citry design can start from it rather than rediscover it.

What the prototype does (old django-components)

Two files carry it: src/django_components/compilers.py (the compiler registry and the compilers
themselves) and src/django_components/management/commands/collectcomponent.py (the static-export
command). Supporting pieces live in dependencies.py and component.py.

1. A compiler registry matched by file type

compilers: List[Tuple[str, Union[str, re.Pattern], CompilerFn]] = [
    ("js", re.compile(r"\.(?:js|ts|jsx|tsx|mjs)$"), ts_compiler),
]
compiler_args: Dict[str, Dict] = {"js": {"check_ts": True}}

get_compiler(filepath) returns the first compiler whose condition matches, where the condition is
either a bare suffix ("js", "css") or a regex. Each compiler is a callable
CompilerFn(entries, args) -> List[Path].

2. Per-component context, grouped by compiler

compile_files(data) takes a list of (component_class, [files]), builds one CompilerCtx per
component, and groups every file under the compiler that claims it, so a compiler that needs all
files of a kind at once (bundlers do) gets them together:

@dataclass
class CompilerCtx:
    html_path: Path
    css_paths: List[Path]
    js_paths: List[Path]
    component: Type["Component"]
    component_path: Path
    component_module_path: str

The intended meta-file design is spelled out in the source comments and is the load-bearing idea:

  1. For each component, define a "meta file" in staticfiles (JSON), keyed by the component hash/name.
  2. The meta file records the paths to the primary dependencies: the html (single), js (list), css (list).
  3. As compilers run one by one they get a reference to this dict, so they can change the html path
    or append more JS/CSS deps. This is what makes CSS code-splitting possible (multiple CSS files on
    the initial load).
  4. After all compilers finish, the meta files are written back to disk.
  5. At runtime, each component looks up its meta-file JSON lazily (loaded only when the component is
    first needed), cached until the server restarts or the files are rebuilt.
  6. Primary CSS is inlined as a <link> to avoid an unstyled-content flash; primary JS is loaded
    the same way as Media.js, just earlier.

3. The TypeScript / JS compiler

ts_compiler:

  1. Optional type check with tsc. Because tsc cannot take both a tsconfig.json and an
    explicit file list on the CLI, it writes a temporary tsconfig.json that extends the user's real
    one and lists the component files in files, then runs tsc --project <tmp> --noEmit --allowJs.
  2. Bundle with esbuild:
    esbuild <entry>=<renamed_in_file> ...
      --bundle --minify --sourcemap
      --entry-names=[dir]/[name]-[hash]
      --chunk-names=$STATIC_ROOT/__dc__/chunks/[name]-[hash]
      --platform=browser --target=chrome80,firefox73,safari13,edge80
      --splitting --format=esm --metafile=metafile.json --outdir=.
    
    Inputs are renamed with an _in suffix first so outputs do not clobber them. --splitting +
    --format=esm is the shared-chunk story (and implies <script type="module"> at runtime). The
    esbuild metafile.json is what tells you the hashed output name for each entry point.

4. The Sass compiler

compile_sass shells out to node running esbuild with esbuild-sass-plugin (loader maps
.scss/.sass/.css to css output). It is a second compiler shape: a small JS build script with the
path mapping JSON-encoded into it.

5. The static-export command

collectcomponent subclasses Django's collectstatic (same arguments), calls collectstatic first,
then:

  1. Runs autodiscovery, iterates _ALL_COMPONENTS.
  2. For each component, write_component_inline_dependencies_to_static(comp_cls) writes the inline
    JS/CSS to STATIC_ROOT under the component's relative path with a hashed filename
    (<stem>-<hash>.<ext>), using comp_cls._comp_path_relative and the (js_lang, js) /
    (css_lang, css) pairs.
  3. Feeds those files into compile_files(...).

The runtime then serves (or redirects to) the static file instead of inlining source, which is the
production asset story (CDN / whitenoise friendly).

6. The source-language contract

Components carry js_lang / css_lang class attributes (default "js" / "css"), the signal a
compiler matches on. The comment hooks at dependencies.py confirm the intended integration point:
the compiled output is exported so it can be post-processed (a # TODO - CALL on_css_postprocess and on_js_postprocess HERE marks where the asset post-process hooks would run).

7. Roadmap left in the comments

  • More compilers: Sass (started), Less, Stylus, Markdown, Pug.
  • i18n / makemessages over component sources.
  • Markdown and Pug run differently: they are applied in render right after the template
    renders, and before any HTML post-process hook, so post-process hooks always see plain HTML.
  • Reload story: full hot reload was deemed too hard; live reload could re-run collectcomponent when
    a file in the component dirs changes, and on runserver start.

How this maps to citry

The framework-agnostic parts port; the Django-specific parts (the collectstatic subclass,
STATIC_ROOT) become citry-neutral equivalents.

  • The compiler registry and per-component grouping (get_compiler, compile_files, CompilerCtx)
    are pure Python and port almost verbatim.
  • The meta-file model (a per-component JSON recording primary html/js/css, written at build,
    looked up lazily at runtime, cached until rebuild) fits citry's no-I/O-at-import rule and the
    dependencies extension's lazy-repopulation approach. It is the language-neutral piece, and the
    natural shared shape if JS/PHP/Go ever grow the same feature.
  • The static-export command becomes a citry CLI command (citry already has ExtensionCommand +
    the citry executable), not a Django management command. The Django collectstatic integration
    becomes a contrib adapter.
  • The js_lang / css_lang contract needs to be added to citry's component class. The
    dependencies extension already owns inline JS/CSS normalization, so the compiler sits between
    "loaded source" and "what dependencies serves".

Prerequisites this feature needs in citry

  1. js_lang / css_lang (or equivalent) metadata on the component class.
  2. The asset post-process hooks (on_js_postprocess / on_css_postprocess, pre-cache) and a
    post-render on_template_postprocess for the Markdown/Pug case. These do not exist in citry yet
    (citry has load-time on_js_loaded / on_css_loaded and on_template_loaded /
    on_template_compiled, but not the post-process pair). Tracked alongside this work.
  3. A static-export CLI command and the lazy meta-file lookup at serialize time, wired into the
    dependencies extension's serving path.

Why core, not an extension

  • It defines the js_lang / css_lang contract and the static-export model that the built-in
    dependencies extension consumes, so it sits below the extension layer.
  • It touches the render pipeline directly (Markdown/Pug transform the rendered HTML before any
    post-process hook).
  • It is the production asset story (hashing, code-splitting, CDN-friendly static files), which a
    templating engine should own rather than leave to a plugin.
  • Tailwind, a SASS/TS workflow, and a minifier are then thin extensions on top of it, rather than each
    re-implementing build orchestration.

Open questions

  • Enable/disable: when compilation is off, the prototype intends to just copy files, and to error if
    it meets a file type that requires compilation (with advice to retype the snippet or enable
    compilation). What is citry's default?
  • Dev vs build: does anything run at dev time, or is it always an explicit export step (plus a live
    reload trigger)?
  • Multi-worker: the in-memory meta cache needs a shared store in multi-worker setups, same constraint
    the dependencies variables-script cache already has.
  • How much of the orchestration is itself pluggable (the compiler registry is the natural seam), and
    whether the node-tool dependency (esbuild/tsc) is an optional extra.

Source pointers (old django-components prototype)

  • src/django_components/compilers.py (the whole registry + ts_compiler + compile_sass)
  • src/django_components/management/commands/collectcomponent.py (static export)
  • src/django_components/dependencies.py (write_component_inline_dependencies_to_static, the
    js_lang/css_lang use, the post-process TODO at the serve path)
  • src/django_components/component.py (js_lang / css_lang / _comp_path_relative attributes)

The prototype is unfinished (debug prints, # TODO guards, a single registered compiler), so this is
a design starting point, not code to lift directly.

Activity

  1. added
    next-sprint
    on Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    next-sprint

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions