Workers with Module Scripts
What you'll learn: How to use type: 'module' when creating Web Workers to load ES6 modules and organize worker code with clean imports.
The Problem with Traditional Workers
Until now, when you created a Web Worker, you had to write self-contained scripts or manually load additional code using importScripts(). This felt clunky compared to modern JavaScript's import/export syntax. But workers can now use ES6 modules!
Using Module Workers
When creating a worker, pass { type: 'module' } as the second argument:
// Main thread
const worker = new Worker('my-worker.js', { type: 'module' });
Inside my-worker.js, you can now use standard import statements:
// my-worker.js (module worker)
import { calculatePrimes } from './math-utils.js';
import { formatResult } from './formatters.js';
self.onmessage = (e) => {
const primes = calculatePrimes(e.data.max);
const formatted = formatResult(primes);
self.postMessage(formatted);
};
Why This Matters
Think of it like organizing a kitchen: Instead of having all your cooking tools crammed into one drawer (a single worker file), you can now use separate containers (modules) for knives, spoons, and spatulas, pulling out exactly what you need when you need it.
Module workers let you:
- Organize code into reusable, testable modules
- Share utility functions between workers and main thread
- Use modern JavaScript features and tooling
- Avoid importScripts() and its limitations
Key Takeaway: Use new Worker(url, { type: 'module' }) to enable ES6 import/export syntax in your workers, making worker code cleaner, more maintainable, and easier to organize across multiple files.