Add a new asset kind#
Problem#
You want discovery to recognise files with a new extension such as .jsx and emit a matching script tag.
Solution#
Register the kind through next.static.default_kinds in AppConfig.ready and point it at a backend renderer method.
Walkthrough#
Register the kind.
from django.apps import AppConfig
from next.static import default_kinds
class NotesConfig(AppConfig):
name = "notes"
def ready(self) -> None:
default_kinds.register(
"jsx",
extension=".jsx",
slot="scripts",
renderer="render_module_tag",
)
See Asset kinds for the register signature.
The module style render_module_tag is reused here because pre compiled JSX ships as ES modules.
Ship the file.
export const NoteCard = ({ title }) => title;
Discovery picks up component.jsx because component is a registered stem and .jsx is now a registered extension.
Emit the asset#
The kind sits in the scripts slot, so {% collect_scripts %} in the layout emits the tag.
No template change is needed.
Custom renderer#
When the new kind needs a tag shape that the bundled methods do not produce, add a renderer method on a custom backend.
from next.static import StaticFilesBackend
class BabelBackend(StaticFilesBackend):
def render_babel_tag(self, url: str, *, request=None) -> str:
return f'<script type="text/babel" src="{url}"></script>'
Register the kind against the new method and register the backend.
Replace the ready registration from the walkthrough with this one, keeping a single registration per kind.
A repeated register call with the same parameters is idempotent, but registering the same kind again with different parameters raises ValueError.
default_kinds.register(
"jsx",
extension=".jsx",
slot="scripts",
renderer="render_babel_tag",
)
NEXT_FRAMEWORK = {
"STATIC_BACKENDS": [
{"BACKEND": "notes.backends.BabelBackend", "OPTIONS": {}}
]
}
A custom renderer costs the kind its client insertion verb, so its assets render on a full page render and are skipped on a partial render.
The next.W074 check reports the kind for that reason.
Keep render_module_tag from the walkthrough when the assets must also arrive through a patch envelope.
Verification#
Reload the page and inspect the HTML source. A script tag points at the JSX file.
Run uv run python manage.py check.
The walkthrough registration reports no warnings, and the custom-renderer variant reports next.W074 for the jsx kind.
See also#
See also
Asset kinds for the registration mechanics. Static backends for the backend renderer methods.