Web Workers provide a way for running scripts in the background, without affecting the performance of the main page. They are especially useful when you need to perform CPU-intensive tasks without freezing the User Interface.
Here are the steps to use TypeScript with Web Workers:
1. **Create worker TypeScript file**: Start by creating a separate TypeScript file for the Web Worker. This file contains the code that will run in the background. Let’s call it ‘worker.ts‘:
self.addEventListener('message', (event: MessageEvent) => {
const data = event.data;
// Perform some expensive operation using data
const result = data.map((x: number) => x * 2); // simple example
(self as any).postMessage(result);
});
Here, we’re listening to the ’message’ event, which is triggered when the main thread sends a message to the worker. The worker then processes the data, and sends a message back to the main thread with the result.
2. **Compile worker TypeScript file**: In order to use this worker file in a web-browser, you need to compile it to JavaScript. For this purpose, create a ‘tsconfig.worker.json‘ configuration file:
{
"compilerOptions": {
"target": "es5",
"lib": ["webworker"],
"module": "none",
"outFile": "./worker.js"
},
"include": ["./worker.ts"]
}
Here, we tell TypeScript compiler to compile ‘worker.ts‘ file to ‘worker.js‘ with target JavaScript version as ‘es5‘. The ‘lib‘ option is set to ‘webworker‘, as we’re working with Web Workers.
Now, run the TypeScript compiler:
tsc --project ./tsconfig.worker.json
This will generate a ‘worker.js‘ file in the specified folder.
3. **Create main TypeScript file**: Next, create the main TypeScript file, e.g., ‘main.ts‘, to communicate with the Web Worker:
if (window.Worker) {
const worker = new Worker('worker.js');
worker.onmessage = (event: MessageEvent) => {
const result = event.data;
console.log('Result from worker:', result);
};
worker.onerror = (event: ErrorEvent) => {
console.error('Error from worker:', event.message);
};
const dataToSend = [1, 2, 3, 4, 5];
worker.postMessage(dataToSend);
} else {
console.error('Web Workers are not supported in your browser.');
}
Here, we first check if the browser supports Web Workers. If supported, we create a new instance of the Worker with ‘worker.js‘, set up the ‘onmessage‘ and ‘onerror‘ event listeners and send a message to the worker using its ‘postMessage‘ method.
4. **Compile main TypeScript file**: Compile the main TypeScript file by adding the required configurations to your ‘tsconfig.json‘ or creating a new configuration file, e.g., ‘tsconfig.main.json‘.
In this example, I’ll create a new configuration file:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "esnext"],
"module": "none",
"outFile": "./main.js"
},
"include": ["./main.ts"]
}
Now, run the TypeScript compiler:
tsc --project ./tsconfig.main.json
5. **Connect the compiled script to your HTML**: Finally, include ‘main.js‘ in your HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>TypeScript and Web Workers</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
That’s it! Now you know how to use TypeScript with Web Workers. You can use this setup as a base to create and utilize Web Workers for more complex operations.