Repository navigation
Description
Design doc:
docs/design/source_languages.mdis the umbrella design for source-language declaration (*_langattributes), 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-stylecollectcomponentexport 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: strThe intended meta-file design is spelled out in the source comments and is the load-bearing idea:
- For each component, define a "meta file" in staticfiles (JSON), keyed by the component hash/name.
- The meta file records the paths to the primary dependencies: the html (single), js (list), css (list).
- 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).- After all compilers finish, the meta files are written back to disk.
- 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.- Primary CSS is inlined as a
<link>to avoid an unstyled-content flash; primary JS is loaded
the same way asMedia.js, just earlier.
3. The TypeScript / JS compiler
ts_compiler:
- Optional type check with
tsc. Becausetsccannot take both atsconfig.jsonand an
explicit file list on the CLI, it writes a temporarytsconfig.jsonthatextendsthe user's real
one and lists the component files infiles, then runstsc --project <tmp> --noEmit --allowJs. - Bundle with esbuild:
Inputs are renamed with an
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=._insuffix first so outputs do not clobber them.--splitting+
--format=esmis the shared-chunk story (and implies<script type="module">at runtime). The
esbuildmetafile.jsonis 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:
- Runs autodiscovery, iterates
_ALL_COMPONENTS. - For each component,
write_component_inline_dependencies_to_static(comp_cls)writes the inline
JS/CSS toSTATIC_ROOTunder the component's relative path with a hashed filename
(<stem>-<hash>.<ext>), usingcomp_cls._comp_path_relativeand the(js_lang, js)/
(css_lang, css)pairs. - 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 /
makemessagesover component sources. - Markdown and Pug run differently: they are applied in
renderright 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
collectcomponentwhen
a file in the component dirs changes, and onrunserverstart.
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
citryCLI command (citry already hasExtensionCommand+
thecitryexecutable), not a Django management command. The Djangocollectstaticintegration
becomes a contrib adapter. - The
js_lang/css_langcontract 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
js_lang/css_lang(or equivalent) metadata on the component class.- The asset post-process hooks (
on_js_postprocess/on_css_postprocess, pre-cache) and a
post-renderon_template_postprocessfor the Markdown/Pug case. These do not exist in citry yet
(citry has load-timeon_js_loaded/on_css_loadedandon_template_loaded/
on_template_compiled, but not the post-process pair). Tracked alongside this work. - 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_langcontract and the static-export model that the built-in
dependenciesextension 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_languse, the post-process TODO at the serve path)src/django_components/component.py(js_lang/css_lang/_comp_path_relativeattributes)
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