LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Current route
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • Kernel Errors
      • Template Compiler Errors
      • Dialog Errors
      • Runtime HTML Errors
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Overview
  • 1. Setting Up the Project
  • 2. Installing Necessary Dependencies
  • 3. Configuring Webpack
  • 4. Creating a Web Worker with TypeScript
  • 5. Integrating the Web Worker into an Aurelia Component
  • 6. TypeScript Configuration
  • 7. Handling Web Worker Types
  • Conclusion

Was this helpful?

Export as PDF
  1. Developer Guides
  2. Recipes

Web Workers Integration

Overview

Web Workers enable background script execution in web applications, enhancing performance by offloading intensive tasks from the main thread. This guide demonstrates how to set up Web Workers in an Aurelia 2 application using TypeScript and Webpack.

1. Setting Up the Project

Ensure you have an Aurelia 2 project configured with Webpack and TypeScript. If not, you can set up a new project using the Aurelia CLI:

npx makes aurelia

Follow the prompts to select Webpack and TypeScript as your desired options.

2. Installing Necessary Dependencies

To handle Web Workers seamlessly, install the worker-loader package, which allows Webpack to import and bundle Web Workers.

npm install worker-loader --save-dev

3. Configuring Webpack

Modify your Webpack configuration to handle .worker.ts files using worker-loader.

webpack.config.js:

module.exports = {
  // ... existing configuration ...
  module: {
    rules: [
      // ... existing rules ...
      {
        test: /\.worker\.ts$/,
        use: { loader: 'worker-loader' }
      }
    ]
  }
};

This configuration directs Webpack to use worker-loader for files ending with .worker.ts.

4. Creating a Web Worker with TypeScript

Create a Web Worker file to perform background tasks.

src/workers/example.worker.ts:

// Ensure TypeScript recognizes the global context inside the worker
/// <reference lib="webworker" />

self.onmessage = (event: MessageEvent) => {
  const { data } = event;
  // Perform intensive computation or task
  const result = data * 2; // Example computation
  self.postMessage(result);
};

The /// <reference lib="webworker" /> directive provides TypeScript with the necessary types for Web Worker contexts.

5. Integrating the Web Worker into an Aurelia Component

Utilize the Web Worker within an Aurelia component.

src/components/my-component.ts:

import { ICustomElementViewModel } from 'aurelia';
import ExampleWorker from '../workers/example.worker.ts';

export class MyComponent implements ICustomElementViewModel {
  result: number | null = null;

  startWorker() {
    const worker = new ExampleWorker();
    worker.postMessage(5); // Sending data to the worker

    worker.onmessage = (event: MessageEvent) => {
      this.result = event.data;
      worker.terminate(); // Terminate the worker when done
    };

    worker.onerror = (error) => {
      console.error('Worker error:', error);
      worker.terminate();
    };
  }
}

src/components/my-component.html:

<template>
  <button click.trigger="startWorker()">Start Worker</button>
  <div if.bind="result !== null">Result: ${result}</div>
</template>

In this setup, clicking the button initiates the Web Worker, which processes data in the background and returns the result without blocking the main thread.

6. TypeScript Configuration

Ensure your tsconfig.json includes the necessary settings for Web Worker support.

tsconfig.json:

{
  "compilerOptions": {
    // ... existing options ...
    "lib": ["dom", "es2015", "webworker"],
    "types": ["webpack-env"]
  },
  // ... existing configuration ...
}

Including "webworker" in the lib array provides TypeScript with the appropriate Web Worker types.

7. Handling Web Worker Types

To prevent TypeScript errors when importing .worker.ts files, declare a module for these imports.

src/types/worker.d.ts:

declare module '*.worker.ts' {
  class WebpackWorker extends Worker {
    constructor();
  }
  export default WebpackWorker;
}

This declaration informs TypeScript about the structure of .worker.ts modules, ensuring proper type checking.

Conclusion

By following this guide, you can effectively integrate Web Workers into your Aurelia 2 application using TypeScript and Webpack. This setup enhances application performance by offloading intensive tasks to background threads, ensuring a responsive user experience.

PreviousWebSockets IntegrationNextPlayground

Last updated 3 months ago

Was this helpful?