Search code examples
moduletypescriptrequirejsweb-worker

Reference a web-worker from a module with a relative path


Long-story short: I have a module baz.ts and a web-worker script worker.ts adjacent to each other in the same folder, but the worker will not load when I'm referencing it with the same relative path from the same file (in case of the worker, I'm obviously loading the js file). Modules compile to the AMD syntax.

I have the following folder layout:

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 modules, foo.ts is imported in tests/test-a/test.ts which is used by the adjacent test.html (this is where the code runs). The rest of the dependencies are visualized easily by the folder layout: foo.ts imports bar.ts, which in turn imports baz.ts and creates a worker from worker.ts -- more precisely, 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
        // ...
    }
}

See how baz.ts and worker.ts are located in the same folder relative to bar.ts (the corresponding .js files are created in place), yet the worker does not load. It tries to load the url tests/foo/bar/worker.js.

How can I make it so that I can reference the worker with the same relative path as I'm importing the module next to it?


Solution

  • It's weird.

    Usually the requests you're making (or resource loading) is relative to the url of the loaded html file, but if that was the case then (as I wrote in the comment) it should have tried to load the worker from tests/test-a/bar/worker.js.

    What you can do is build an absolute url for your worker and use that, something like:

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

    Probably not ideal, but it should work.