@nazfy/worker
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

Astro Worker

Astro Worker is a polyfill for using server-side Web Workers in Astro, powered by web-worker.

NPM Version NPM Downloads Open in StackBlitz

npm install @astropub/worker

Usage

Import @astropub/worker in your Astro configuration.

import worker from "@astropub/worker"
import { defineConfig } from "astro/config"

export default defineConfig({
  integrations: [
    worker(),
  ],
})

Creating a Worker

Create a worker in any Astro project.

---
/** @file /src/scripts/worker.ts */

addEventListener("message", (event) => {
  console.log("client said:", event.data)

  postMessage(event.data)
})

Using a Worker

Import the worker into Astro frontmatter.

---
/** @file /src/pages/index.astro */

const worker = new Worker("../scripts/worker.ts", { type: "module" })

worker.addEventListener("message", (event) => {
  console.log("worker said:", event.data)
})

worker.postMessage("Hello")
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="viewport" content="width=device-width" />
    <meta name="generator" content={Astro.generator} />
    <title>Example</title>
  </head>
  <body>
    <h1>Example</h1>
  </body>
</html>

Alternatively, import the worker into a client-side script.

---
/** @file /src/pages/index.astro */
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="viewport" content="width=device-width" />
    <meta name="generator" content={Astro.generator} />
    <title>Example</title>
  </head>
  <body>
    <h1>Example</h1>
  </body>
</html>
<script>
  const worker = new Worker("../scripts/worker.ts", { type: "module" })

  worker.addEventListener("message", (event) => {
    console.log("worker said:", event.data)
  })

  worker.postMessage("Hello")
</script>

Enjoy!


Code original to this project is licensed under the MIT No Attribution License.

Code from web-worker is licensed under the Apache License (Apache-2.0), copyright Jason Miller.

/@nazfy/worker/

    Package Sidebar

    Install

    npm i @nazfy/worker

    Weekly Downloads

    2

    Version

    0.1.0

    License

    (MIT-0 AND Apache-2.0)

    Unpacked Size

    24.3 kB

    Total Files

    7

    Last publish

    Collaborators

    • nazfy