Reputation: 51
I am trying to build ionic app that uses tensorflowjs with coco-ssd model to detect objects on images from camera. Also, I need to be able to toggle flashlight while using camera.
When I use model's detection function just as promise
call with await
, it stops another 'threads' until detection is done. This is preventing flashlight to toggle instantly, and after button press (button that toggles flashlight), it has to wait for like half of a second to switch on or off.
I've decided to use coco-ssd in web worker, but I found out that I can't import node modules in web workers because of this error:
SyntaxError: import declarations may only appear at top level of a module worker-test.js:1
I've searched for some similar questions, but almost nobody imports modules in web workers, and the ones that do - they do it in javascript. To enable module importing in js you just have to pass another param to worker constructor: new Worker('url/to/script.js', {type: 'module'})
But the thing is, you can't pass second parameter to worker constructor in typescript, so I can't create a worker like that.
Relevant files:
test.page.ts
...
ionViewDidEnter() {
this.testWorker();
}
testWorker() {
const worker = new Worker('assets/worker-test/worker-test.js');
worker.onmessage = function(event) {
console.log('onmessage');
console.log(event.data);
};
worker.postMessage('From main thread');
}
...
worker-test.js
import * as cocoSsd from '@tensorflow-models/coco-ssd';
postMessage("posting message");
onmessage = function(data) {
console.log('In worker');
console.log(data.data);
console.log(model);
};
let model;
cocoSsd.load().then((res) => {
model = res;
});
ionic info:
ionic (Ionic CLI) : 4.12.0 (~/.nvm/versions/node/v12.4.0/lib/node_modules/ionic)
Ionic Framework : @ionic/angular 4.6.2
@angular-devkit/build-angular : 0.13.9
@angular-devkit/schematics : 7.3.9
@angular/cli : 7.3.9
@ionic/angular-toolkit : 1.5.1
Thanks for help in advance.
Upvotes: 3
Views: 3722
Reputation: 18381
The compilation option of typescript should target either es2015 or esnext.
{
...
"compilerOptions": {
"lib": ["esnext", "webworker"],
}
}
Additionnaly adding "webworker"
will indicate that the project will use the webworker api.
Upvotes: 3