首页 > 解决方案 > 使用 svelte 进行调试

问题描述

我正在尝试深入研究 Svelte 3 (v3.7.1),它运行良好……在包含外部 CSS (bootstrap) 时遇到了一些绊脚石。

但是,我似乎无法理解的一件事是在我的浏览器中调试苗条的应用程序

我发现一篇关于 svelte github 问题的帖子说我只需要{@debug}在我的代码中包含某个地方,以便让浏览器在“那个点”中断,这样我就可以调试和检查当前状态。

但是:这根本不起作用。即使{@debug}存在,即使我打开了开发人员工具,也没有中断。

为了调试我的代码,我必须做什么?

编辑:我认为您需要了解我的设置

我使用一个 node/express web 服务器,它app.use(express.static('svelteclient/public'))从 svelte 项目的子文件夹中为编译的 svelte 客户端提供服务。

代码摘录:

<script>

   import { onMount } from 'svelte';

   let searches = ["angular", "deno", "svelte", "stencil"];
   let tweets = {};

   let currentImage = null;
   let currentYTUrl = "";

   for(let search of searches) {
      tweets[search] = [];
   }

   let socket = io();

   let modal = null;
   let ytmodal = null;

   onMount(() => {
      modal = UIkit.modal('#mymodal');
      ytmodal = UIkit.modal('#myytmodal');
   });

...
</script>

<style>
   .uk-panel-badge .uk-badge {
      cursor: pointer;
   }
</style>

{@debug}


<div class="uk-grid" data-uk-grid-margin>
   {#each searches as search}
   <div class={'uk-width-medium-1-' + searches.length}>
      ...
   </div>
   {/each}
</div>

Chrome 版本为 75.0.3770.142

标签: svelte

解决方案


{@debug}一种模板语法,可用作console.log.

你可以把它放在你的html代码中,然后打开devtools你的浏览器。

如果您的组件在打开时执行该@debug语句devtools,它将自动暂停执行。

编辑

如果你有这个苗条的代码

<script>
    let name = 'world';
</script>

{@debug name}

<h1>Hello {name}!</h1>

它将编译为

// more code
c: function create() {
    {
        const {  } = ctx;
        console.log({ name }); // <-- Note those 2 lines
        debugger; // <-- corresponding to the @debug statement
    }

    t0 = space();
    h1 = element("h1");
    t1 = text("Hello ");
    t2 = text(name);
    t3 = text("!");
    add_location(h1, file, 6, 0, 56);
}
// more code

每次渲染组件时它都会运行。包括第一次。如果所述值更改没有触发新的渲染,则它不受值更改的约束。

如果要将控制台日志绑定到值更改,则需要在脚本中使用响应式语句

$: console.log(name);

或者

$: value, console.log('value has been updated');

debugger语句在 Chrome 76 和 Firefox Quantum 68 中停止脚本执行


推荐阅读