feat: migrate reassigned deriveds to `$derived` (#15581)

pull/15582/head
Paolo Ricciuti 6 months ago committed by GitHub
parent c1ae8953aa
commit 33d118f8a2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
feat: migrate reassigned deriveds to `$derived`

@ -19,6 +19,7 @@ import { migrate_svelte_ignore } from '../utils/extract_svelte_ignore.js';
import { validate_component_options } from '../validate-options.js'; import { validate_component_options } from '../validate-options.js';
import { is_reserved, is_svg, is_void } from '../../utils.js'; import { is_reserved, is_svg, is_void } from '../../utils.js';
import { regex_is_valid_identifier } from '../phases/patterns.js'; import { regex_is_valid_identifier } from '../phases/patterns.js';
import { VERSION } from 'svelte/compiler';
const regex_style_tags = /(<style[^>]+>)([\S\s]*?)(<\/style>)/g; const regex_style_tags = /(<style[^>]+>)([\S\s]*?)(<\/style>)/g;
const style_placeholder = '/*$$__STYLE_CONTENT__$$*/'; const style_placeholder = '/*$$__STYLE_CONTENT__$$*/';
@ -113,6 +114,16 @@ function find_closing_parenthesis(start, code) {
return end; return end;
} }
function check_support_writable_deriveds() {
const [major, minor, patch] = VERSION.split('.');
if (+major < 5) return false;
if (+minor < 25) return false;
return true;
}
const support_writable_derived = check_support_writable_deriveds();
/** /**
* Does a best-effort migration of Svelte code towards using runes, event attributes and render tags. * Does a best-effort migration of Svelte code towards using runes, event attributes and render tags.
* May throw an error if the code is too complex to migrate automatically. * May throw an error if the code is too complex to migrate automatically.
@ -952,7 +963,11 @@ const instance_script = {
const reassigned_bindings = bindings.filter((b) => b?.reassigned); const reassigned_bindings = bindings.filter((b) => b?.reassigned);
if ( if (
reassigned_bindings.length === 0 && // on version 5.25.0 deriveds are writable so we can use them even if
// reassigned (but if the right side is a literal we want to use `$state`)
(support_writable_derived
? node.body.expression.right.type !== 'Literal'
: reassigned_bindings.length === 0) &&
!bindings.some((b) => b?.kind === 'store_sub') && !bindings.some((b) => b?.kind === 'store_sub') &&
node.body.expression.left.type !== 'MemberExpression' node.body.expression.left.type !== 'MemberExpression'
) { ) {

@ -0,0 +1,10 @@
<script>
let name = 'world';
$: upper = name.toUpperCase();
</script>
<input bind:value={name} />
<input bind:value={upper} />
{upper}

@ -0,0 +1,10 @@
<script>
let name = $state('world');
let upper = $derived(name.toUpperCase());
</script>
<input bind:value={name} />
<input bind:value={upper} />
{upper}
Loading…
Cancel
Save