I followed the example provided in the docs:
// main.qml
import QtQuick 2.0
import "script.mjs" as MyScript
Item {
width: 100; height: 100
MouseArea {
anchors.fill: parent
onClicked: {
MyScript.showCalculations(10)
console.log("Call factorial() from QML:",
MyScript.factorial(10))
}
}
}
// script.mjs
import { factorial } from "factorial.mjs"
function showCalculations(value) {
console.log(
"Call factorial() from script.js:",
factorial(value));
}
// factorial.mjs
export function factorial(a) {
a = parseInt(a);
if (a <= 0)
return 1;
else
return a * factorial(a - 1);
}
Running qmlscene on main.qml and mouse click on the window triggers the following error:
main.qml:12: TypeError: Property 'showCalculations' of object TypeError: Type error is not a function
Expected output: Must calculate factorial twice and print to console
If I fix script.mjs by exporting showCalculations function like this:
export function showCalculations(value) {
I get factorial calculated only once, but expected twice. Output is the following:
qml: Call factorial() from script.js: 3628800
main.qml:13: TypeError: Property 'factorial' of object TypeError: Type error is not a function
I also tried to rename script.mjs to script.js, but that breaks import factorial.js, so it does not help.
One more issue is that docs state that "Sometimes it is desirable to have the functions made available in the importing context without needing to qualify them. In this case ECMAScript modules and the JavaScript import statement should be used without the as qualifier."
I tried:
import "script.mjs"
But I get error:
main.qml:4 Script import requires a qualifier
Expected: import must happen without issues and one can call showCalculations() and factorial() without qualifiers.
I created a bug for it, but it can take long until the guys have a look at it. Maybe someone here knows how to get the exact behavior described in the docs. I need to import an ECMAScript module, not just a JS file.