You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte构建时Icon组件触发TypeError报错,寻求问题排查方案

Svelte Icon组件构建报错:TypeError: Cannot read properties of undefined (reading 'reassigned')

我编写了一个Svelte的Icon组件,代码如下:

<script>
    export let { href, brand, anim, color} = '';
    let icon;

    function addClass(){
        icon.classList.add(anim, color);
    }

    function removeClass(){
        icon.classList.remove(anim, color);
    }
</script>

<a
    {href}
    target="_blank"
    on:mouseenter={addClass}
    on:mouseleave={removeClass}
    class="w-7 h-7 pl-4 first:pl-0 pr-8 grid group"
>
    <i bind:this={icon} class={`fa-brands fa-xl ${brand}`} />
</a>

该组件需接收href、brand、anim、color四个props,实现鼠标悬停在<a>标签上时为<i>元素添加动画与颜色类,鼠标移出时移除对应类的功能。

我在根页面page.svelte中这样使用该组件:

<Icon href="https://www.linkedin.com/" brand="fa-linkedin" anim="fa-beat" color="text-yellow-500" />

但构建项目时出现如下错误:

file: C:/Users/Dev/frontend projects/svelte-portfolio/src/lib/Icon.svelte
error during build:
TypeError: Cannot read properties of undefined (reading 'reassigned')
at file:///C:/Users/Dev/frontend%20projects/svelte-portfolio/node_modules/svelte/src/compiler/compile/Component.js:1351:13


错误原因

核心问题是props解构的语法错误:你试图将对象解构赋值给空字符串'',这完全不符合对象解构的语法规则。Svelte编译器在处理这种非法写法时,触发了内部逻辑错误,从而抛出了上述报错。

解决方案

1. 修正props声明的正确写法

有两种规范的方式来声明带默认值的props:

  • 方式一:逐个声明每个prop并设置默认值
    <script>
        export let href = '';
        export let brand = '';
        export let anim = '';
        export let color = '';
        let icon;
    
        function addClass(){
            icon.classList.add(anim, color);
        }
    
        function removeClass(){
            icon.classList.remove(anim, color);
        }
    </script>
    
  • 方式二:使用对象解构,目标为一个空对象并给每个属性设置默认值
    <script>
        export let { href = '', brand = '', anim = '', color = '' } = {};
        let icon;
    
        function addClass(){
            icon.classList.add(anim, color);
        }
    
        function removeClass(){
            icon.classList.remove(anim, color);
        }
    </script>
    

2. 更符合Svelte风格的实现(推荐)

避免手动操作DOM的classList,改用状态变量+类绑定的方式,代码更简洁且更符合Svelte的响应式逻辑:

<script>
    export let href = '';
    export let brand = '';
    export let anim = '';
    export let color = '';
    let isHovered = false;
</script>

<a
    {href}
    target="_blank"
    on:mouseenter={() => isHovered = true}
    on:mouseleave={() => isHovered = false}
    class="w-7 h-7 pl-4 first:pl-0 pr-8 grid group"
>
    <i 
        class="fa-brands fa-xl {brand}"
        class:{anim}={isHovered}
        class:{color}={isHovered}
    />
</a>

内容的提问来源于stack exchange,提问作者JStack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 23:23:15