Skip to content

"$0 is not defined in {expression}" error on class attribute of a svelte:elementΒ #15392

@bfanger

Description

@bfanger

Describe the bug

We're using cn utility to set the tailwind classes, but in 5.20.3 this stopped working:

<script lang="ts">
  function cn(className) {
    return className;
  }
  const tag = "div";
</script>

<svelte:element this={tag}
  class={cn("font-bold")}
>
</svelte:element>

Compiles to:

import 'svelte/internal/disclose-version';
import 'svelte/internal/flags/legacy';
import * as $ from 'svelte/internal/client';

export default function App($$anchor) {
	function cn(className) {
		return className;
	}

	const tag = "div";
	var fragment = $.comment();
	var node = $.first_child(fragment);

	$.element(node, () => tag, false, ($$element, $$anchor) => {
		$.template_effect(() => $.set_class($$element, 0, $.clsx($0)));
	});

	$.append($$anchor, fragment);
}

The cn("font-bold") code is is no longer in the compiled output.

In 5.20.2 the code worked and compiled to:

import 'svelte/internal/disclose-version';
import 'svelte/internal/flags/legacy';
import * as $ from 'svelte/internal/client';

export default function App($$anchor) {
	function cn(className) {
		return className;
	}

	const tag = "div";
	var fragment = $.comment();
	var node = $.first_child(fragment);

	$.element(node, () => tag, false, ($$element, $$anchor) => {
		let attributes;

		$.template_effect(($0) => attributes = $.set_attributes($$element, attributes, { class: $0 }, undefined, $$element.namespaceURI === $.NAMESPACE_SVG, $$element.nodeName.includes('-')), [() => cn("font-bold")], $.derived_safe_equal);
	});

	$.append($$anchor, fragment);
}

Reproduction

https://svelte.dev/playground/hello-world?version=5.20.4#H4sIAAAAAAAAE22OQU7EMAxFr2J51UoF9p22EjtWcwHMIpO4JVLqVIk7gKrcHWVGICGxfd__fR8oZmXs8YVDiPARU3DQsPPKrsUOZx84Y_96oH5t9a4C7H5az9v2mK8ctLKLyfwft1GURTP2OGSb_KYQjCwjoWbCiQRg3sWqjwJWGhtMzmezcgtHzQAS654EfoNTxYWE1EbJCmoWGIHQ-SvhiWR4us9MJCTD_Y-eA68sCvru83ioWUq13JzjYaUhnKPowyUGR9gWkukm-lOesEPlT8Ve087lrXwDBykhvT8BAAA=

Logs

System Info

System:
    OS: macOS 15.3.1
    CPU: (12) arm64 Apple M3 Pro
    Memory: 473.27 MB / 36.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 23.7.0 - /opt/homebrew/bin/node
    Yarn: 1.22.22 - ~/Library/pnpm/yarn
    npm: 10.9.2 - /opt/homebrew/bin/npm
    pnpm: 10.5.0 - ~/Library/pnpm/pnpm
    bun: 1.1.34 - ~/.bun/bin/bun
  Browsers:
    Chrome: 133.0.6943.127
    Safari: 18.3
  npmPackages:
    svelte: 5.20.4 => 5.20.4

Severity

blocking an upgrade

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions