Skip to content

fix: evaluate dynamic image sources once - #16900

Open
teemingc wants to merge 12 commits into
version-3from
teemingc-avoid-duplicate-function-calls
Open

fix: evaluate dynamic image sources once#16900
teemingc wants to merge 12 commits into
version-3from
teemingc-avoid-duplicate-function-calls

Conversation

@teemingc

@teemingc teemingc commented Aug 22, 2026

Copy link
Copy Markdown
Member

Fixes: #12231

This PR tries to add a Svelte declaration tag if the image source is an expression that should only be computed once.

  • It requires a newer version of Svelte to do so, which is a a breaking change. uses the old declaration tag by wrapping it in an if block that is always true. This works in both legacy and runes mode
  • It also replaces svelte-markup-parser with the official Svelte parser so that we can check for colliding declaration references.

Please don't delete this checklist! Before submitting the PR, please make sure you do the following:

  • It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
  • This message body should clearly illustrate what problems it solves.
  • Ideally, include a test that fails without this PR but passes with it.

Tests

  • Run the tests with pnpm test and lint the project with pnpm lint and pnpm check

Targeted validation: enhanced-img formatting and type checks, unit tests, integration tests, and diff checks.

Changesets

  • If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running pnpm changeset and following the prompts. Changesets that add features should be minor and those that fix bugs should be patch. Please prefix changeset messages with feat:, fix:, or chore:.

Added a patch changeset for @sveltejs/enhanced-img.

Edits

  • Please ensure that 'Allow edits from maintainers' is checked. PRs without this option may be closed.

teemingc and others added 9 commits August 22, 2026 02:55
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@pkg-svelte-dev

pkg-svelte-dev Bot commented Aug 22, 2026

Copy link
Copy Markdown

Install the latest version of @sveltejs/kit from 4059e21:

pnpm add https://pkg.svelte.dev/@sveltejs/kit/c/4059e215e76868fcd216b1640e6e3836ef08c168

Open in pkg.svelte.dev: https://pkg.svelte.dev/repos/kit/pr/16900

@changeset-bot

changeset-bot Bot commented Aug 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 4059e21

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@sveltejs/enhanced-img Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@svelte-docs-bot

Copy link
Copy Markdown

Comment thread packages/enhanced-img/src/vite-plugin.js
/**
* @param {Expression | Super} expression
*/
function is_reference(expression) {

@teemingc teemingc Aug 22, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if this needs to account for more expression types such as https://github.com/sveltejs/dts-buddy/blob/c1c53c6b93e5db189243540dcb193bf8cd2b0bd1/src/utils.js#L550

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Comment thread packages/enhanced-img/src/vite-plugin.js Outdated
vercel Bot and others added 2 commits August 22, 2026 10:47
…nst ...}` declaration tag, which throws a hard compile error ("Declaration tags cannot be used in legacy mode") in any legacy-mode component, and is also non-reactive in the cases where it does compile.

This commit fixes the issue reported at packages/enhanced-img/src/vite-plugin.js:419

## The bug

To avoid evaluating a computed `src` expression multiple times (once per template
position), `dynamic_img_to_picture` in `packages/enhanced-img/src/vite-plugin.js`
(line ~419) caches it in a Svelte **declaration tag**:

```js
`${src_expression ? `{const ${src_var_name} = ${src_expression}}\n` : ''}...`
```

Note the bare `{const}`, not `{@const}`. This has two problems, one of them fatal.

### 1. Hard compile error in legacy-mode components (primary failure)

Declaration tags (`{const ...}`) were only added in Svelte 5.56 and are **not
allowed in legacy-mode components** — the compiler throws:

> `Declaration tags cannot be used in legacy mode`

Verified against `svelte@5.56.10`, a component's mode determines the outcome:

| Component contents | Result with `{const}` |
| --- | --- |
| `export let` (legacy) | **THROW** |
| `$:` reactive statement (legacy) | **THROW** |
| `<svelte:options runes={false} />` | **THROW** |
| plain `let` only (ambiguous) | OK |
| runes (`$props`, `$state`) | OK |

So **any legacy-mode Svelte component** containing
`<enhanced:img src={dynamicExpression}>` will **fail to compile**. This is a
regression introduced by the "evaluate dynamic sources once" change (commit
`1d1bd60`), which also bumped the `svelte` peer dep from `^5.0.0` to `^5.56.0`.

Why the existing test suite missed it: the fixture `test/Input.svelte` only uses
`let foo` (ambiguous mode, no `export`/no runes), which is one of the few
configurations where `{const}` happens to compile — masking the bug.

### 2. Non-reactive even when it compiles (secondary)

In the ambiguous/runes cases where `{const}` does compile, it emits a plain
once-evaluated binding at the top of the component function. Compiling
`{const v = large ? big : small}` (where `large` is `$state`) yields:

```js
const v = $.get(large) ? big : small;   // read ONCE, outside any effect
$.if(node, ($$render) => { if (typeof v === 'string') ... });  // static v
$.template_effect(() => $.set_attribute(img, 'src', v));       // static v
```

The picture never updates when the source expression depends on reactive state,
unlike the previous inline behavior.

## The fix

Emit a **reactive** `{@const}` instead. Because `{@const}` is only valid as an
immediate child of a block/component, the whole picture is wrapped in an
always-true `{#if true}` block:

```js
if (src_expression) {
  return `{#if true}{@const ${src_var_name} = ${src_expression}}\n${picture}\n{/if}`;
}
return picture;
```

`{@const}` compiles to a `$.derived(...)` (reactive, memoized once-per-update) and
every downstream use becomes `$.get(v)` — restoring reactivity while still
evaluating the expression only once. Crucially, `{@const}` is valid in **both**
legacy and runes mode and has existed since **Svelte 5.0**, so it fixes the
compile error too.

Simple references (`image`, `object.image`) are still inlined
(`should_declare === false`) and are unaffected.

## Bonus: revert the peer-dep bump

Because `{@const}` works on Svelte 5.0, the `svelte` peer-dependency bump to
`^5.56.0` in `packages/enhanced-img/package.json` is no longer needed. The patch
reverts it back to `^5.0.0` (the value prior to commit `1d1bd60`).

## Tests

Updated `test/markup-plugin.spec.js` and the `test/Output.svelte` snapshot to
expect the reactive `{#if true}{@const ...}` wrapping. The `get_image(i)`
single-evaluation assertions still hold.

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: teemingc <chewteeming01@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Don't call functions multiple times

2 participants