Files
advanced-camera-card/rollup.config.js
T
Dermot Duffy ea251ca988 perf(bundle): lazy-load the nunjucks template engine (#2535)
Closes #2531.

## Summary

The full `nunjucks` templating engine (~226KB) plus `ha-nunjucks`
(~46KB) — roughly **272KB, ~13% of the eager entry chunk** — was
statically imported and downloaded by every card on initial load, even
though templates only apply when a config value contains a `{{ … }}` /
`{% … %}` delimiter. Most cards use no templates and never need the
engine.

This defers the engine behind a dynamic `import('ha-nunjucks/dist')` so
it ships in a separate, on-demand chunk instead of the eager
`card-*.js`.

## Approach

The render path (`TemplateRenderer.renderRecursively`) is **kept
synchronous** — it is called from many synchronous hot paths
(condition/trigger evaluators, picture-elements rendering, actions,
folder matchers), and making it async would be a large, high-risk
refactor of the evaluation core.

Instead:

- **New `src/card-controller/templates/engine.ts`** — a module-level
singleton lazy loader (`loadTemplateEngine()` / `getTemplateEngine()`)
shared across all `TemplateRenderer` instances, plus a
`containsTemplate()` delimiter helper.
- **Delimiter gating** — strings without a delimiter never touch the
engine (the overwhelming majority of renders).
- **Pre-warm at config time** — because every template string originates
in the config, a new mandatory `TEMPLATE_ENGINE` initialization aspect
loads the engine before first render whenever the config contains a
delimiter. This **guarantees no raw `{{ … }}` flash**: content/condition
rendering is blocked until the engine is present for template-using
cards. Cards without templates never load it.

## Result

- nunjucks + ha-nunjucks move out of the eager chunk into a separate
chunk fetched only when a card actually uses templates.
- No change to the synchronous public render API; condition/trigger
evaluation core untouched.

## Tests

- New `engine.ts` loader coverage (concurrent load, cached reuse,
not-loaded fallback).
- The 11 existing test files that render real (delimiter-bearing)
templates declare their dependency explicitly via
`beforeAll(loadTemplateEngine)` — no global/implicit setup hook.
- Full suite green (4764 tests), lint and ts-prune clean, per-file 100%
coverage maintained for the affected directories.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_016ykWemdkZrgywvC71pHc6c

---
_Generated by [Claude
Code](https://claude.ai/code/session_016ykWemdkZrgywvC71pHc6c)_
2026-06-30 17:45:13 -07:00

141 lines
4.1 KiB
JavaScript

import commonjs from '@rollup/plugin-commonjs';
import image from '@rollup/plugin-image';
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import terser from '@rollup/plugin-terser';
import typescript from '@rollup/plugin-typescript';
import gitInfo from 'rollup-plugin-git-info';
import serve from 'rollup-plugin-serve';
import styles from 'rollup-plugin-styler';
import svgo from 'rollup-plugin-svgo';
import { visualizer } from 'rollup-plugin-visualizer';
const watch = process.env.ROLLUP_WATCH === 'true' || process.env.ROLLUP_WATCH === '1';
const dev = watch || process.env.DEV === 'true' || process.env.DEV === '1';
// Opt-in dev server: `rollup -c --watch --environment SERVE`. Off by default
// for deployments that read output from the filesystem.
const serveEnabled = process.env.SERVE === 'true' || process.env.SERVE === '1';
/**
* @type {import('rollup-plugin-serve').ServeOptions}
*/
const serveopts = {
contentBase: ['./dist'],
host: '0.0.0.0',
port: 10001,
allowCrossOrigin: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
};
/**
* @type {import('rollup').RollupOptions['plugins']}
*/
const plugins = [
gitInfo.default({ enableBuildDate: true, updateVersion: false }),
styles({
modules: false,
// Behavior of inject mode, without actually injecting style
// into <head>.
mode: ['inject', () => undefined],
sass: {
includePaths: ['./node_modules/'],
},
}),
svgo(),
image({ exclude: '**/*.svg' }),
nodeResolve({
browser: true,
}),
commonjs({
include: 'node_modules/**',
sourceMap: false,
}),
typescript({
sourceMap: dev,
inlineSources: dev,
exclude: ['dist/**', 'tests/**/*.test.ts'],
}),
json({ exclude: 'package.json' }),
replace({
preventAssignment: true,
values: {
'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production'),
__ADVANCED_CAMERA_CARD_RELEASE_VERSION__:
process.env.RELEASE_VERSION ?? (dev ? 'dev' : 'pkg'),
},
}),
serveEnabled && serve(serveopts),
!dev && terser(),
visualizer({
filename: 'visualizations/treemap.html',
template: 'treemap',
}),
];
const outputEntryTemplate = {
entryFileNames: 'advanced-camera-card.js',
dir: 'dist',
chunkFileNames: (chunk) => {
// Add "lang-" to the front of the language chunk names for readability.
if (
chunk.facadeModuleId &&
chunk.facadeModuleId.match(/localize\/languages\/.*\.json/)
) {
return 'lang-[name]-[hash].js';
}
if (chunk.facadeModuleId && chunk.facadeModuleId.match(/ha-nunjucks/)) {
return 'templates-[hash].js';
}
return '[name]-[hash].js';
},
format: 'es',
sourcemap: dev,
};
const CIRCULAR_DEPENDENCY_IGNORE_REGEXP = /(ha-nunjucks|ts-py-datetime|zod\/v4)/;
/**
* @type {import('rollup').RollupOptions}
*/
const config = {
input: 'src/card.ts',
// Specifically want a facade created as HACS will attach a hacstag
// queryparameter to the resource. Without a facade when chunks re-import the
// card chunk, they'll refer to a 'different' copy of the card chunk without
// the hacstag, causing a re-download of the same content and functionality
// problems.
preserveEntrySignatures: 'strict',
output: [
outputEntryTemplate,
// Continue to include the old file name for backwards compatibility.
{
...outputEntryTemplate,
entryFileNames: 'frigate-hass-card.js',
},
],
plugins: plugins,
// These files use `this` at the toplevel, which causes rollup warning spam on
// build: `this` has been rewritten to `undefined`.
moduleContext: {
'./node_modules/@formatjs/intl-utils/lib/src/diff.js': 'window',
'./node_modules/@formatjs/intl-utils/lib/src/resolve-locale.js': 'window',
},
// Ignore circular dependencies from underlying libraries.
onwarn: (warning, defaultHandler) => {
if (
warning.code === 'CIRCULAR_DEPENDENCY' &&
warning.ids.some((id) => id.match(CIRCULAR_DEPENDENCY_IGNORE_REGEXP))
) {
return;
}
defaultHandler(warning);
},
};
export default config;