用 svelte 调试

dev*_*l69 9 svelte

我正在尝试深入研究 Svelte 3 (v3.7.1) 并且它运行良好……在包含外部 CSS(引导程序)方面有一些绊脚石。

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

我发现了一篇关于 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>
Run Code Online (Sandbox Code Playgroud)

Chrome 版本是 75.0.3770.142

Mor*_*ish 12

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

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

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

编辑

如果你有这个苗条的代码

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

{@debug name}

<h1>Hello {name}!</h1>
Run Code Online (Sandbox Code Playgroud)

它将编译为

// 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
Run Code Online (Sandbox Code Playgroud)

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

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

$: console.log(name);
Run Code Online (Sandbox Code Playgroud)

或者

$: value, console.log('value has been updated');
Run Code Online (Sandbox Code Playgroud)

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

  • 是的,调试语句可能不包含在构建版本中。将 console.logs 留在生产应用程序中通常会令人不悦,因此 svelte 编译器废弃它们是有道理的。 (2认同)

dev*_*l69 6

感谢您的所有好提示

问题是:在进行生产编译时,每个debugger语句都会从生成的bundle.js 中删除

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

编辑:另一个解决方案:

在运行之前更改 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()
Run Code Online (Sandbox Code Playgroud)