Angular 17 running in SSR mode cannot find Web Worker script

180 Views Asked by At

I have an Angular 17 web application running with SSR enabled. When I run the application with ng serve I get the following error (terminal and a popup on the web UI).

[plugin:vite:import-analysis] Failed to resolve import "./assets/js/worker.js" from "/index.html?html-proxy&index=0.js". Does the file exist?
/index.html:2:31
1  |  
2  |      import { asyncRun } from './assets/js/worker.js';
   |                                ^
3  |      window.__worker__ = { asyncRun };
4  |

My index.html is pretty standard and the section relevant to the error looks like the following.

<script type="module">
  import { asyncRun } from './assets/js/worker.js';
  window.__worker__ = { asyncRun };
</script>

I understand that starting with Angular 17, they are using Vite (as opposed to Angular 16, they were using Webpack by default). When I try the same approach in an Angular 16 application, I don't see this error.

Anyone know a workaround for this issue?

1

There are 1 best solutions below

3
Naren Murali On

UPDATE

Angular has it own way of handling web workers, you can read it in the docs: anuglar-web-workers

I followed the instructions and got the web worker running pretty easily, also note, that the script you provided is a bit confusing, there is no onSuccess method, but we can use this to leverage the web worker functionality!

/// <reference lib="webworker" />

addEventListener('message', (e) => {
  const message = `hello, world ${new Date()}`;
  self.postMessage({ message });
});

Stackblitz Demo -> cd test -> npm i -> npm run start -> check the console for web worker output!


Could you create a separate script file called workerRunner.js and move the contents of the script tag inside that and place it on the assets folder, then in the angular.json you can directly run the script using the scripts array!

angular.json

        ...
        "tsConfig": "tsconfig.app.json",
        "inlineStyleLanguage": "scss",
        "assets": ["src/favicon.ico", "src/assets"],
        "styles": ["src/styles.scss"],
        "scripts": ["src/assets/webWorker.js"],
        "server": "src/main.server.ts",
        "prerender": true,
        ...

stackblitz -> cd test -> npm i -> npm run start