How to import javascript file to qml worker script

4.2k views Asked by At

I'm creating an application in me where I want to download data from the internet. To avoid blocking of main thread I created a WorkerScript file. This works fine, but I need to abstract certain parts (like authorization, proper header, etc) to general-purpose functions.

Unfortunately, I haven't found a way to import the js file to the js file that serves as a worker thread. ".import" causes syntax error.

How can I achieve this?

Thank you.

Edit:

This is the relevant part from qml file:

Page {
    WorkerScript {
          id: myWorker
          source: Qt.resolvedUrl("loadDetails.js")
          onMessage:  {}
      }
}

And this is loadDetails.js:

.import "jsonrpc.js" as Jrpc
WorkerScript.onMessage = function(message) {
    // This is where I want to call functions from included file
}
3

There are 3 answers

2
Duzy Trzmiel On BEST ANSWER

See documentation provided by Oleg:

Worker script can not use .import syntax.

3
Oleg Shparber On

I guess you have missed a qualifier in the import statement. The proper syntax is:

.import "filename.js" as Qualifier

See Qt Documentation for your case.

0
tanghus On

This is more of a meta answer, as it is also addressed to the other answerers.

The Qt Documentation can at times be ambiguous. In the WorkerScript Documentation it states that:

Worker scripts that are plain JavaScript sources can not use .import syntax. Scripts that are ECMAScript modules can freely use import and export statements.

Except that doesn't seem to be the case. I have tried all different kinds of imports:

// example.mjs
.import "test.mjs" as Test
.import * as Test from "test.mjs";
import "test.mjs" as Test
import * as Test from "test.mjs";
import { test } from "test.mjs"

So it's obvious that it doesn't work, but the documentations states that it does - and that it doesn't...