使用 svelte 进行调试

Debugging with svelte

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

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

我在 post 上发现了一个 github 问题,指出我只需要在我的代码中的某处包含 {@debug} 以使浏览器在 [=32= 处中断] 这样我就可以调试和检查当前状态。

但是:这根本行不通。即使 {@debug} 存在,即使我打开了开发者工具也没有中断。

我需要做什么才能调试我的代码?

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

我使用一个 node/express 网络服务器来为编译后的 svelte 客户端提供服务,作为来自 svelte 项目子文件夹的 app.use(express.static('svelteclient/public'))

代码摘录:

<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

{@debug} 是一个 template syntax,可以替代 console.log

您可以将它放在您的 html 代码中,然后打开浏览器 devtools

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

编辑

如果你有这个精巧的代码

<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

中停止脚本执行

{@debug} 语句仅在您调试的变量发生变化时触发断点。文档在最后一段中暗示了这一点,"The {@debug} tag without any arguments will insert a debugger statement that gets triggered when any state changes, as opposed to the specified variables."(参见 https://svelte.dev/docs#debug

以下代码在 3 秒后在断点处停止。

<script>
  let name = 'world';

  setTimeout(() => {
    name = 'moon';
  }, 3000)
</script>

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

可以在 https://svelte.dev/repl/761771bd8eb9462796bba3373dfa46c7?version=3.7.1

看到一个工作示例

谢谢你所有的好提示

问题是:为生产编译时,每个 debugger 语句都会从结果 bundle.js

中剥离

解决方案:改为npm run dev,然后立即停止实时重新加载服务器以避免URL关于socket.io

的怪异组合

编辑:另一个解决方案:

将rollup.config.js改成运行npm run build:

    plugins: [
        svelte({
            // Always enable run-time checks
            dev: true,
            ...
        }),
        ...
        // NOT use terser, otherwise debugger will be stripped!
        //production && terser()