4

Is it possible to import javascript files in a QJSEngine (QT 5.6)?

Example 1:

Text in plainTextEdit:

.import "./jsimport.js" as Test
var x = Test.y;
console.log(x);

c++:

void MainWindow::on_pushButton_clicked()
{
    QJSEngine engine;
    engine.installExtensions(QJSEngine::AllExtensions);

    QJSValue result = engine.evaluate(ui->plainTextEdit->toPlainText());
    qDebug() << "isError:" << result.isError();
    qDebug() << "resultString:" << result.toString();
    if(result.hasProperty("lineNumber"))
        qDebug() << "property lineNumber:" << result.property("lineNumber").toInt();
}

text in jsimport.js file:

var y = 42;

result:

isError: true
resultString: "ReferenceError: Test is not defined"
property lineNumber: 2

Example 2:

Text in PlainTextEdit:

.import "./jsimport.js"

same c++ code

result:

isError: true
resultString: "SyntaxError: File import requires a qualifier"
property lineNumber: 1

It seems that there is some functionality for an import, because of the last error.

Mike
  • 53
  • 1
  • 7

2 Answers2

1

In newer Qt versions, import can be used in QJSEngine.

Use ECMA-262/ES6 syntax instead of QML leading-dot syntax:

import { Test } from "./jsimport.js"
var x = Test.y;
console.log(x);

./jsimport.js

export Test = {
  y: 54
}

I believe this was probably added as part of the upgrade to ES6 and ES7 in Qt5.12:

As it says, you may also use ::importModule() to preload/initialize ES6 modules from the C++ side.

Will Chen
  • 482
  • 4
  • 12
0

The .import statement does not work with QJSEngine. QJSEngine is just a bare interpreter, if you want to have some "import" functionality you might switch to QQmlEngine, which is built on top of QJSEngine: http://doc.qt.io/qt-5/qtqml-syntax-imports.html#qml-import-path

With QJSEngine you basically need to manually populate the js global object (and QtCreator sintax checker will not recognize the statements you use across the different files).

Miguel El Merendero
  • 2,054
  • 1
  • 17
  • 17
  • oh ok. Can i use the QQmlEngine for just javascript? – Mike Jul 01 '16 at 10:50
  • I don't know, nor can I point you to some example of that. In my project I ended up using QJSEngine and it works just fine as long as you don't expect it to have Qml features. – Miguel El Merendero Jul 02 '16 at 07:29
  • Might be because the answer is old, but QJSEngine does support imports: https://doc.qt.io/archives/qt-5.12/qjsengine.html#evaluating-scripts – Michael Sep 11 '22 at 17:09
  • 1
    @Michael I assume `import` probably was added as part of the ES6 and ES7 update in Qt5.12: https://doc.qt.io/qt-5/whatsnew512.html#qt-qml-module – Will Chen May 16 '23 at 14:51