@lopatnov/worker-from-string
v2.1.0
Published
Create Web Workers from strings at runtime. A lightweight TypeScript library for dynamic worker generation in browsers.
Downloads
132
Maintainers
Readme
@lopatnov/worker-from-string
A library that converts string values into Web Worker objects in the browser. Create dynamic Web Workers at runtime without separate script files.
Table of Contents
Installation
npm install @lopatnov/worker-from-stringBrowser (CDN):
<!-- Development version -->
<script src="https://lopatnov.github.io/worker-from-string/dist/worker-from-string.js"></script>
<!-- Production (minified) version -->
<script src="https://lopatnov.github.io/worker-from-string/dist/worker-from-string.min.js"></script>Usage
ES Modules
import workerFromString from "@lopatnov/worker-from-string";CommonJS
const workerFromString = require("@lopatnov/worker-from-string");Browser (UMD)
const workerFromString = window.workerFromString;API
workerFromString(...textValues: string[]): Worker
Creates a Web Worker from string values.
| Parameter | Type | Description |
|--------------|------------|------------------------------------------------|
| textValues | string[] | One or more strings containing the worker code |
Returns: Worker — a new Web Worker instance.
Examples
Basic Usage
const workerCode = `
self.onmessage = function(e) {
postMessage('Hello ' + e.data);
};
`;
const worker = workerFromString(workerCode);
worker.onmessage = function(e) {
console.log(e.data); // "Hello world"
};
worker.postMessage('world');Multiple String Arguments
const imports = "importScripts('https://example.com/lib.js');";
const logic = "self.onmessage = function(e) { postMessage(process(e.data)); };";
const worker = workerFromString(imports, logic);With TypeScript
import workerFromString from "@lopatnov/worker-from-string";
const worker = workerFromString(`
self.onmessage = (e: MessageEvent) => {
const result = e.data * 2;
postMessage(result);
};
`);
worker.onmessage = (e: MessageEvent) => {
console.log('Result:', e.data);
};
worker.postMessage(21);Demo
- Live Editor: https://lopatnov.github.io/worker-from-string/
- QUnit Tests: https://lopatnov.github.io/worker-from-string/test/index.html
Contributing
Contributions are welcome! Please read CONTRIBUTING.md before opening a pull request.
- Bug reports → open an issue
- Questions → Discussions
- Found it useful? A star on GitHub helps others discover the project
Built With
- TypeScript — strict typing throughout
- Rollup — bundled to ESM, CJS, and UMD formats
- QUnit — browser-based unit testing framework
- Blob API — in-memory worker script creation
- URL.createObjectURL — dynamic worker URL generation
License
Apache-2.0 © 2019–2026 Oleksandr Lopatnov · LinkedIn
