migrate() function performs a best-effort migration of Svelte 4 code to Svelte 5, transforming legacy syntax to use runes, event attributes, and render tags.
Signature
Parameters
The Svelte 4 component source code to migrate
The filename of the component (used for debugging and self-referencing components)
Whether to generate TypeScript syntax. If not specified, the migrator will infer from the source code.
Return Value
The migrated Svelte 5 code. May include
@migration-task comments for manual review.What Gets Migrated
The migrator handles:- Reactive declarations (
$:) →$derivedand$effect - Exported props (
export let) →$props()destructuring - Reactive statements →
$effect.pre()orrun() - Event handlers (
on:click) → event attributes (onclick) - Slots → Snippets (
{@render children()}) <svelte:component>with dynamic this →{@const}or$derived<svelte:self>→ Self-import- CSS selector scoping →
:global()where needed beforeUpdate/afterUpdateimports → Removed if unused
Usage Examples
Basic Migration
Migrating Props with TypeScript
Migrating Slots to Snippets
Migrating Event Handlers
Programmatic Migration
Handling Migration Tasks
When the migrator can’t automatically handle certain patterns, it adds comments:@migration-task in the migrated code and address these manually.
Using with CLI
Svelte provides a CLI migration tool:Limitations
- CSS preprocessors: CSS is blanked during migration. Use a preprocessor-aware tool if needed.
- Complex reactive patterns: Some complex
$:patterns may not migrate cleanly. - beforeUpdate/afterUpdate: Must be migrated manually to runes or lifecycle functions.
- Store auto-subscription:
$storesyntax is not migrated (still works in Svelte 5). - Component events: Must be migrated to callback props manually.
Best Practices
- Commit before migrating - Always have a clean git state
- Review the output - Don’t blindly accept migrations
- Test thoroughly - Run your test suite after migration
- Migrate incrementally - Start with leaf components
- Read migration tasks - Address all
@migration-taskcomments
Related
- Svelte 5 Migration Guide
- compile() - Compile migrated code
- Runes Documentation