苗条的调试

时间:2019-08-07 09:02:37

标签: svelte

我正试图深入研究Svelte 3(v3.7.1),它运作得很好……在包括外部CSS(引导程序)时有一些绊脚石。

但是,尽管如此,我似乎无法绕开的一件事就是在浏览器中调试这个精巧的应用程序

我发现了一个关于svelte github问题的文章,指出我只需要在代码中的某个地方包含{@debug}即可使浏览器在“该点”处中断,以便我可以调试和检查当前状态。 / p>

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

我必须做什么才能调试我的代码?

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

我使用一个节点/ express Web服务器,它从svelte项目的子文件夹中以app.use(express.static('svelteclient/public'))的形式提供已编译的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

3 个答案:

答案 0 :(得分:5)

{@debug}template syntax,可以代替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中执行脚本

答案 1 :(得分:1)

{@debug}语句仅在您调试的变量更改时触发断点。该文档在最后一段中暗示了这一点:“ {@ debug}标记不带任何参数,将插入一个调试器语句,该调试器语句将在状态发生变化(与指定变量相反)时触发。” (请参阅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上看到一个工作示例

答案 2 :(得分:1)

感谢您的所有好提示

问题是:在进行生产编译时,每个debugger语句都会从结果bundle.js中剥离

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

编辑:另一个解决方案:

在运行npm run build之前更改rollup.config.js:

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