DEV Community

Cover image for 5 Things AI Can't Do, Even in Svelte.Js
DevUnionX
DevUnionX

Posted on

5 Things AI Can't Do, Even in Svelte.Js

This report examines in depth the limitations in Svelte.js development process with AI-assisted tools. Considering Svelte's compiler-based architecture, technical and conceptual challenges were analyzed in five topics: component semantics and composition, reactivity model and complex state flows, compile-time versus runtime behavior and edge cases, accessibility and ARIA integration, and performance with build toolchain and scale compatibility. In each topic Svelte-specific rules were explained and supported with concrete error examples AI makes and case studies.

For instance in Reactivity Model topic, Svelte's reactivity based on variable assignments gets emphasized. When you update values inside object or array, for compiler to detect this you need to make assignment to variable itself. If this gets neglected in AI-assisted code, updates don't reflect to DOM. Additionally limitations arising from Svelte's compile-first design were examined. For instance html tag might not do correct hydration after SSR, or reactive classes like MediaQuery don't give correct result during SSR because no browser measurement exists. In each section, code examples and failure modes were addressed and solution paths discussed. For example to prevent async errors, using onMount and tick, cleanup with effect in code snippets shown.

Table at end of writing compares Svelte code generated by AI with code written by human in criteria like correctness, accessibility, maintainability, package size, and corporate compliance. Finally a mermaid diagram showing developer plus AI workflow summarizes process steps. Findings clearly reveal that human supervision and experience remain indispensable in Svelte projects. For this study, primarily official Svelte documents and release notes were examined. Reactivity, compile-time features, and performance recommendations were scanned in detail in Svelte documentation. Then feedback from Svelte developer community including GitHub issues, blog posts, StackOverflow questions was evaluated. For accessibility standards, MDN and W3C/WCAG sources were reviewed. Literature and case studies analyzing errors in code AI code assistants wrote were also compiled.

Obtained data was processed in depth in five main topics specific to Svelte. Under each topic, technical explanations, concrete error scenarios, example codes, and solution strategies were presented. Each section of report was supported with results using relevant and priority sources. Svelte components require tight integration with HTML. Interaction between components is provided with props and createEventDispatcher. Semantically, developer should always prefer valid HTML tags and avoid unnecessary wrapping. For instance when creating list item with li tag, this must definitely be inside ul or ol. Though not an error from Svelte itself, AI sometimes can make similar semantic incompatibilities.

Another situation is bind:this usage. Svelte offers bind:this directive to get reference to DOM nodes. In following example, an input element gets bound to nameEl variable getting reference and after form submission gets pulled back to focus with focus. Script. Let name equals empty string. Let nameEl for DOM element reference. Function addTodo. Add new task operation. Name equals empty string. nameEl.focus for giving focus back to input. Script. Input bind:value equals name bind:this equals nameEl id equals todo-input. Button on:click equals addTodo disabled equals not name showing Add.

Code generated by AI might skip this kind of bind:this usage leading to focus management problems. Also correct positioning of component contents with Svelte's slot mechanism is important. For instance modal component content should be placed with slot. AI sometimes might suggest transition with methods like direct innerHTML, which can be problematic in terms of accessibility and maintainability.

Developer strategies: semantic HTML usage in AI code should always be reviewed. For instance instead of adding role equals button to elements that aren't button, use real button when possible. Props and event dispatch structures should be defined correctly. Missing createEventDispatcher usage in AI code should be carefully checked. If submission preventDefault or custom directive usage needed, should be manually added. When operations toward focus requiring bind:this usage are seen in code, should be manually added if AI skipped. Ultimately component composition should pass through human supervision.

Svelte offers compiler-based reactivity system. State changes typically get tracked with assignment equals or dollar colon reactive declarations. Important rule: for Svelte to understand a variable updated, variable name needs to be on left side of assignment. For instance in reference types like arrays and objects when element update done, Svelte might not detect this. In following MDN example, completed field of items inside todos array gets updated but Svelte doesn't notice. Const checkAllTodos equals with completed parameter. Todos.forEach with t arrow t.completed equals completed. Todos equals todos notifying Svelte of change.

In this code, though each item of array updated, Svelte doesn't observe this update because array itself didn't change. As solution, reassignment done like todos equals todos, this way compiler understands variable got modified. Alternatively updating each item from array's index or assigning completely new array also works, for example todos equals todos.map with t arrow spread t with completed. AI assistants generally might not remember this reactive assignment rule. For instance might do t.completed equals directly inside todos.forEach and finish code, in this case UI doesn't update. Similarly in complex state management, usage of derived stores can be neglected. As example:

Import writable derived from svelte/store. Export const cartItems equals writable empty array. Export const cartTotal equals derived cartItems with dollar items arrow items.reduce with sum item arrow sum plus item.price times item.qty starting at 0. This way when items in cart change, total automatically updates. AI might miss that it should use derived instead of just simple forEach loop.

Failure modes: frequent error related to reactive updates is DOM not renewing due to forgetting variable assignment. Outside above todos example, in situations like obj.property plus equals 1, Svelte thinks obj as a whole didn't change. Additionally when using a store, mixing dollar store versus get store or using structures compiler cannot track gives wrong result. As real case, developers sometimes experience memory leak with store subscriptions not cleaned, for example not canceling subscription in onDestroy. Such cleanups can be overlooked in code written by AI.

Developer strategies: check reactive dollar colon declarations and direct variable assignments. If object or array modification exists in AI code, ensure relevant variable gets reassigned. If this isn't possible, create new data structures with methods like map or slice doing same operation. Apply derived or subscription subscribe usage correctly in stores. Do manual supervision in complex state flows. For instance test dollar colon blocks, validate cyclic assignments get cleaned. Ultimately you should adapt code to Svelte's reactivity rules in way compiler will understand.

One of Svelte's most important features is generating code optimized at compile time. This design doesn't require framework with no virtual DOM and lightens runtime. However this approach brings some edge cases. For instance in Svelte 5 version there's bug report about html tag usage, this marker isn't validated after SSR leading to unexpected behavior. AI-assisted code cannot see such version-specific errors so can fall into same trap. Svelte also enables Server-Side Rendering SSR. But some APIs don't work in SSR. For instance Svelte's MediaQuery class cannot give correct value server side because no browser measurement, leading to content change during hydration.

If this gets overlooked in AI code, production and browser output can be incompatible. Lifecycle hooks also matter. Code inside onMount runs only on client. AI sometimes can put operations requiring DOM access like document or window access in places that shouldn't run in SSR. This creates both error and SEO problem. Example showing only dispensable data requests should be made in load function below. If AI fetches large amount of data inside load, render time gets longer.

Script context equals module. Export async function load with fetch parameter. Const res equals await fetch /api/posts. Return posts equals await res.json. Script. SvelteKit documentation emphasizes data not needed shouldn't be pulled to client side immediately. This might not be considered in AI code.

Developer strategies: review Svelte code AI generated considering compile time. Ensure codes requiring SSR are separated with conditions like onMount or dollar client. Check whether custom directives AI uses like use:action and bind are in right place. Track version-specific errors from Svelte announcement pages, for example html problem. For performance, apply code splitting lazy-load where SvelteKit supports dynamic import. In above load example, extra data can be precompiled with prerender or pending properties can be used. Briefly pay attention to runtime and compile-time distinctions avoiding breaking assumptions Svelte is optimized for.

In applications developed with Svelte, accessibility is provided with semantic HTML and correct ARIA usage. Official documents emphasize all elements requiring user interaction should be accessible and usable with keyboard. For instance in a form when input field created dynamically using bind:this equals inputEl, focus should be set correctly with inputEl.focus function. AI assistants might skip focus management and event properties like Enter and Escape key. In MDN Svelte example, user experience improved by calling cancel function when Escape key pressed with on:keydown. Such keyboard shortcuts generally don't get added to AI outputs.

Another point is usage of ARIA attributes and semantic tags. When selecting tag names in Svelte components, screen reader compatibility should be considered. For instance real button should be used instead of div role equals button. Example situation: in modal or popup component, aria-modal equals true and role equals dialog should be added and focus trap precautions taken. This is generally missing in AI code. Additionally attributes like aria-label and aria-labelledby in HTML tags must definitely be added if buttons or links aren't clear. In MDN advanced Svelte guide, focus order arranged so focus loss doesn't happen with tab key. AI outputs might not pay attention to focus shifts.

Developer strategies: adhere strictly to semantic HTML usage and ARIA guides. Every tag like button, input, form in AI code's needed accessibility attribute like aria attributes and label-id association should be checked. For focus management and keyboard access, handlers like tabindex and on:keydown should be added. Consciously use focus-visible in places where focus emphasis gets lost with CSS. After getting reference to DOM nodes with bind:this in Svelte, focus giving strategy should be considered in component lifecycle like onMount. Don't forget to manually provide these details AI might bypass.

In Svelte applications package size and build optimization carry great importance. Svelte's compiler structure provides tree-shaking built-in, but external dependencies should still be checked in bundler configuration. For instance AI code frequently generates by importing entire large libraries like import underscore from lodash, whereas with proper structuring only needed functions should be included like import uniq from lodash-es. In SvelteKit documents, noted that code with static import will load with page. If lazy load forgotten in AI outputs, initial load grows unnecessarily. In developer blog above, dynamic loading of components like modals or admin panels with import inside onMount was recommended. AI-assisted structures not doing this worsen performance.

Another matter mentioned in SvelteKit performance notes is version updates. Svelte 5 is faster and smaller than Svelte 4, Svelte 4 also faster and smaller than 3 is recommended. This is an optimization missed when AI assistants recommend old version codes or don't track updates. Additionally AI generally skips package analysis. As developer should examine bundle size with tools like rollup-plugin-visualizer and vite-bundle-visualizer, replace large dependencies.

Example showing modal loading with dynamic code splitting. Script. Import onMount from svelte. Let ModalComponent. onMount async arrow function. Const module equals await import ./Modal.svelte. ModalComponent equals module.default with Modal component now loaded. Script. If ModalComponent. svelte:component this equals ModalComponent. If. With this method, code segmentation done instead of always import Modal from ./Modal.svelte in code from AI.

Developer strategies: manually check package imports in AI code, prefer including only needed functions. Make dynamic import usage mandatory in compiler and bundler settings. For instance in SvelteKit load functions, pull only critical data instead of loading everything and create static page with prerender equals true. For interactive elements like image lazy load and UI components, use built-in loading equals lazy attributes. Finally during production pre-build process like npm run build, check build minify true settings. These optimizations AI will overlook should be applied manually.

The following table presents general comparison in Svelte context between AI generation and human generation. Correctness low prone to reactivity and lifecycle errors, can make SSR cliche errors like html versus High with compiler warnings considered and edge cases tested. Accessibility medium with focus order and ARIA attribute generally forgotten versus Good with semantic element and keyboard navigation properly set.

Maintainability low with repetitions and lack of explanation in auto-generated code pieces versus High with code component-based organized and enriched with comment lines. Package Size large high due to unnecessary dependencies and static imports versus Low minimal with only needed modules and dynamic imports. Brand Fidelity weak with CSS and theme compatibility, style guide inconsistency visible versus High with configuration compliant with corporate style rules provided.

The mermaid flowchart shows developer checking Svelte code from AI primarily for component structure and props/emits. Then reactive rules like variable assignments get inspected. SSR and CSR distinction like onMount and dollar browser usage gets reviewed. Next step includes accessibility with keyboard navigation and ARIA and performance optimizations including bundle size and lazy-loading. At each step when deficiency detected, correction made, at end of process code approved. Details AI skipped get completed with manual review.

Top comments (0)