无法创建异步 Svelte 操作

Can't create asynchronous Svelte action

我正在尝试在 Svelte 上创建异步操作(use:action 指令),当我尝试以下 "non-async" 函数时它工作正常

export default function typewriter(node, options) {
    for (const letter of elementsText[elIndex]) {
        if (!reverse && el.textContent === elementsText[elIndex].join('')) return
        if (reverse && el.textContent === '') return
        if (Array.isArray(interval)) {
            const randomInterval = Math.floor(Math.random() * interval.length)
            // this function needs an `await`
            await sleep(interval[randomInterval])
        } else if (typeof interval == 'number') {
            // this function requires an `await`
            sleep(interval)
        }
        !reverse ? (el.textContent += letter) : (el.textContent = el.textContent.slice(0, -1))
    }
}

但是当我尝试将上面的代码转换为异步函数时,出现以下错误(可能是 抛出的错误)

Uncaught (in promise) ReferenceError: regeneratorRuntime is not defined

Adapted from johnny answer on

我用@babel/plugin-transform-runtime。该插件描述为:

Externalize references to helpers and builtins, automatically polyfilling your code without polluting globals. What does this actually mean though? Basically, you can use built-ins such as Promise, Set, Symbol etc as well use all the Babel features that require a polyfill seamlessly, without global pollution, making it extremely suitable for libraries.

它还支持 async/await 以及 ES 6 的其他内置插件。

纱线:

$ yarn add -D @babel/plugin-transform-runtime

npm:

$ npm i -D @babel/plugin-transform-runtime

.babelrc中添加运行时插件

{
  "plugins": [
    ["@babel/transform-runtime", { "regenerator": true }]
  ]
}