Skip to content

Leka74/easythread

Repository files navigation

Easythread

A collection of plugins for improving the developer experience with Web Workers and Worker Threads across different bundlers and environments.

Requirements

  • Node.js: >=20.0.0
  • pnpm: >=8.0.0 (for development)

Packages

Installation

For Vite (Browser/Web Workers)

npm install @easythread/vite
# or
pnpm add @easythread/vite

For Rollup/Node.js (Worker Threads)

npm install @easythread/rollup
# or
pnpm add @easythread/rollup

Configuration

Vite

// vite.config.js
import { defineConfig } from 'vite'
import easythreadPlugin from '@easythread/vite'

export default defineConfig({
  plugins: [easythreadPlugin()],
})

Rollup

// rollup.config.js
import easythreadPlugin from '@easythread/rollup'

export default {
  plugins: [easythreadPlugin()],
}

Usage

Simple usage

/** @easythread */
function heavyComputation(data: number[]) {
  let result = 0;
  for (let i = 0; i < data.length; i++) {
    result += Math.pow(data[i], 2);
  }
  console.log("Result", result);
}

// Use the function as if it's running on the main thread
const data = [1, 2, 3, 4, 5];
heavyComputation(data);

// Main thread continues execution immediately
console.log("Main thread is not blocked!");

Return value from the easythread

/** @easythread */
async function complexCalculation(x: number, y: number): Promise<number> {
  // Simulate a time-consuming calculation
  return Promise.resolve(x * y + Math.sqrt(x + y));
}

// Use the function and handle the returned promise
complexCalculation(10, 20).then((result) => {
  console.log("Calculation result:", result);
});

console.log(
  "This will be logged immediately, before the calculation completes."
);

Anonymous function

/** @easythread */
(() => {
  console.log("This is an anonymous function running in a worker thread");
  // Perform some heavy computation here
  for (let i = 0; i < 1000000000; i++) {
    // Simulating complex work
  }
  console.log("Anonymous function completed its work");
})();

console.log("Main thread continues execution immediately");

Using out-of-scope variables

Easythread can automatically detect and pass variables that are defined outside the function's scope:

const multiplier = 2;
const message = "Calculation complete!";

/** @easythread */
function outOfScopeExample(x: number): Promise<number> {
  const result = x * multiplier;
  console.log(message, result);
  return Promise.resolve(result);
}

outOfScopeExample(10).then((result) => {
  console.log("Result:", result);
});

In this example, multiplier and message are automatically detected and passed to the worker thread.

Using imported libraries

Easythread now supports using imported functions and values within worker threads:

import { calculateHash } from 'crypto-lib';
import utils from './utils';

/** @easythread */
async function processData(data: string): Promise<string> {
  const hash = calculateHash(data);
  const result = utils.transform(hash);
  return result;
}

// The function will automatically import the required modules in the worker
const result = await processData("some data");

Import Support Details

  • Named imports: import { func } from 'module'
  • Default imports: import module from 'module'
  • Namespace imports: import * as module from 'module'
  • Relative imports: import { func } from './local-module'
  • Dynamic loading: Imports are loaded dynamically when the worker starts

Limitations

While Easythread can handle most primitive values and plain objects, there are some limitations on what can be passed to a worker thread:

  1. Functions: Worker threads cannot receive functions as arguments or use functions from the outer scope.
  2. DOM elements: Workers don't have access to the DOM, so DOM elements can't be passed or used.
  3. Complex objects: Objects with circular references or those that can't be cloned (like Symbols) cannot be passed to workers.
  4. Class instances: Instances of custom classes may lose their methods when passed to a worker.
  5. Some node_modules: Not all npm packages are compatible with Web Workers (e.g., those requiring Node.js APIs or DOM access).

About

Make worker threads easy

Resources

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •