I am currently trying add a webworker to my Angular 9 project using Angular CLI 9.1.7. This webworker should run some calculations using mathjs 7.
However, importing mathjs into the webworker always results in the following error in the browser console. If I don't import mathjs, the worker runs without a problem.
index.js:7 Uncaught ReferenceError: window is not defined
at Object../node_modules/seed-random/index.js (index.js:7)
at __webpack_require__ (bootstrap:19)
at Module../node_modules/mathjs/es/function/probability/util/seededRNG.js (seededRNG.js:1)
at __webpack_require__ (bootstrap:19)
at Module../node_modules/mathjs/es/function/probability/pickRandom.js (pickRandom.js:1)
at __webpack_require__ (bootstrap:19)
at Module../node_modules/mathjs/es/factoriesAny.js (factoriesAny.js:1)
at __webpack_require__ (bootstrap:19)
at Module../node_modules/mathjs/es/entry/pureFunctionsAny.generated.js (pureFunctionsAny.generated.js:1)
at __webpack_require__ (bootstrap:19)
The referenced line is
var GLOBAL = typeof global === 'undefined' ? window : global;
and is part of the seed-random library used in mathjs.
I know that window
is typically undefined in a webworker, however global
should be set as far as I understand.
In the webpack config that the angular-devkit uses internally, I found the follwing section:
{
plugins: [new WorkerPlugin({
globalObject: false,
plugins: [getTypescriptWorkerPlugin(wco, workerTsConfigPath)],
})],
}
There, I already tried setting globalObject
to self
or this
in my local node_modules
folder, however this did not solve the problem.
I also don't see an option in the angular.json
file to provide any additional configuration for the webworker to fix this problem, so I am unsure what to do to make this work.
In the mathjs documentation, I found an example of using it in a webworker, so I assume it should also be possible using the Angular CLI.
I created a GitHub repo with a minimal working example. If you run it with
npm install
npm start
you can see the described error in the browser console.
So my question is: How can I use mathjs in an Angular CLI webworker?
I opened an issue on the math.js GitHub where another workaround was proposed: It seems to be sufficient to just change the import from
import { sqrt } from 'mathjs';
to
import { sqrt } from 'mathjs/dist/math.js';
to fix the webworker.
This workaround is fairly simple and seems to work. However, this problem might be solved in future versions of math.js. It might make sense to check the issue for updates on this.