Utilize a web-worker in a module by referencing it using a relative path

Basically, I have a situation where there is a module called baz.ts and a web-worker script named worker.ts placed side by side in the same directory. However, despite being in close proximity to each other, the worker script fails to load when referenced using the relative path from the same file (loading the js file for the worker). The modules are compiled to the AMD syntax.

The folder structure looks like this:

MyApp
|-- tests
|   `-- test-a
|       |-- test.html
|       `-- test.ts
`-- lib
    |-- foo.ts
    `-- foo
        |-- 
        |-- bar.ts   <-- 'bar/worker' loaded here
        `-- bar
            |-- baz.ts
            `-- worker.ts

foo.ts, bar.ts, baz.ts are all modules. foo.ts is imported in tests/test-a/test.ts which is utilized by the adjacent test.html (where the code execution takes place). The dependency tree can be easily deciphered from the structure: foo.ts imports bar.ts, which then imports baz.ts and utilizes a worker from worker.ts -- specifically, from the compiled .js output:

bar.ts

import {Baz} from "./bar/baz";

export class Bar {
    constructor() {
        var worker = new Worker("./bar/worker.js"); // same path as the above import
        // ...
    }
}

Notice how both baz.ts and worker.ts reside within the same directory in relation to bar.ts (the corresponding .js files are generated accordingly), yet the worker script doesn't load successfully. It attempts to load from the url tests/foo/bar/worker.js.

What steps should be taken to ensure that I can refer to the worker script with the same relative path as when importing the adjoining module?

Answer №1

It's quite peculiar.

Typically, the requests you're sending (or resource loading) are relative to the URL of the loaded HTML file. However, if that were true, then (as mentioned in the comment), it would have attempted to load the worker from tests/test-a/bar/worker.js.

One possible solution is to construct an absolute URL for your worker and utilize it, such as:

let url = new URL("lib/foo/bar.js", window.location.origin);
let worker = new Worker(url.toString());

While not necessarily ideal, this approach should get the job done.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with React.js code not being detected in TSX file (Visual Studio 2015 Update 1 RC)

Currently, I am utilizing Visual Studio 2015 with update 1 release candidate. Interestingly, I have managed to successfully incorporate React.js code and syntax highlighting within a .JSX file. However, when it comes to a .TSX file, nothing seems to be wor ...

callback function for file upload completion in Angular 4

My Angular 4 app has a simple file upload feature that works well. However, I'm facing an issue with the onSuccessItem callback not triggering every time a file is uploaded. The callback only triggers after the first upload, and I need it to trigger f ...

What is the process for importing string data into an Excel document using Angular?

I'm encountering a situation where I have non-JSON data coming from the backend. How can I efficiently write this type of data into an Excel file? To handle this task, I've utilized XLSX and FileSaver libraries by referencing an example on Plunk ...

ngx-charts - Horizontal Bar Charts dynamically adjust bar thickness when data is updated

Using Angular and ngx-charts to display data fetched from the server works perfectly on initial load trigger with the ngOnInit() method calling getStats() function. Everything loads as expected: https://i.sstatic.net/8OsbD.png However, upon clicking the ...

Seeking assistance in addressing a TypeScript error related to typecasting in Angular 9

After updating Angular from version 4 to 9, I have encountered some errors that I am struggling to resolve. Here is a snippet of my code: this.getTrades().then((trades) => { console.log(trades); this.trades = new MatTableDataSource<Trade> ...

Model Field Serialization in Angular HttpClient

Is there a way to designate the serialized name (similar to @SerializedName in Gson) of a field in a model class when receiving JSON responses from a server? For example, if the server response includes fields like start_date or some_date, but I want my m ...

Utilizing declaration files in a TypeScript application to provide global exposure of types

Recently, I've delved into the world of typescript and set up a project with numerous React components written in typescript. To streamline development, we decided to extract all necessary types for these components into a separate file named types.d. ...

Why isn't my Angular/Typescript Subscription causing a change in the variable for my Arrow function?

Why Isn't My Arrow Function in Subscription of Observer Changing the Local Variable bool? upVoteAvailability(i: number) { let bool!:boolean ; this.featureService.upVoteAvailable(i).subscribe(x=> { bool = x as boolean console.log ...

Angular integration problem with aws-amplify when signing up with Google account

I am attempting to integrate AWS-Amplify(^4.3.0) with angular-12 and typescript (4.3.5). I have followed the documentation to configure amplify properly, but when trying to start the app, I encountered some amplify errors as shown below. Warning: D:\G ...

Customizing DatePipe in Angular components within the node_modules directory

Issue: I am facing a challenge with an external library in my Angular application that contains components using the Angular DatePipe internally to format dates in the 'shortDate' style. Unfortunately, I am unable to switch to a different compone ...

Tips for excluding test files in next.js when building

I am currently developing a next.js application with tests integrated within the page directory structure. In order to achieve this, I have made necessary configurations in the next.config.js file. const { i18n } = require('./next-i18next.config' ...

What are the specific purposes of utilizing semantic versioning (semver) notation within the package.json file?

Could someone clarify the specific distinctions between the semver notations found in package.json file? I'd appreciate a detailed explanation. ...

Is it possible to preserve the numerical type of a percentage when applying number formatting?

After applying number formatting, I converted a numerical value of 150 to 150.00%. Although this is the desired display format with the percentage sign included, the data type remains as string instead of number. Is there a method to convert it back to a ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

Bypass React Query execution when the parameter is null

I am facing an issue with a react query problem. I have a separate file containing all the queries: const useFetchApTableQuery = (date: string): UseQueryResult => { const axiosClient = axios.create() const fetchApTableQuery = async (): Promise<A ...

A specialized solution designed to avoid loops in references

Is there a method to create a general solution that can prevent circular variables in JavaScript? This solution should be effective for any level of depth or type of circular reference, not limited to the variable itself... So far I've come up with t ...

Retrieving subcollection data in Firestore using Angular

I am facing the challenge of extracting data from a subcollection within my database structure. Within my main collection products, there are documents that have a nested subcollection called reviews. products/prodID/reviews/reviewID Here is my interface ...

Issue with the scoring algorithm using Angular and Spring Boot

Hello, I have created a scoring algorithm to calculate scores, but I encountered an error in "salaireNet". ERROR TypeError: Cannot read properties of null (reading 'salaireNet') at ScoringComponent.calculateScore (scoring.component.ts:33:55) ...

Capture and handle JavaScript errors within iframes specified with the srcDoc attribute

My current project involves creating a React component that can render any HTML/JavaScript content within an iframe using the srcDoc attribute. The challenge I am facing is implementing an error handling system to display a message instead of the iframe ...

Issue: Import statement cannot be used outside a module in Appium

Encountering the following error while working on a colleague's laptop, so it appears that there is no issue with the code itself. It could be related to my local packages but I am not entirely certain. node version: v18.20.1 npm version : 10.5.0 impo ...