Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. QJsEngine cannot use import syntax
Forum Updated to NodeBB v4.3 + New Features

QJsEngine cannot use import syntax

Scheduled Pinned Locked Moved Solved QML and Qt Quick
7 Posts 2 Posters 1.5k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U Offline
    U Offline
    UremSept
    wrote on 9 Oct 2019, 15:54 last edited by
    #1

    I follow the documentation, using import, but I am getting an error.

    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QString fileName = ":/test.jsm";
        QFile scriptFile(fileName);
        if (!scriptFile.open(QIODevice::ReadOnly)){
            // handle error
            qDebug()<<"open file fail!";
        }
        QTextStream stream(&scriptFile);
        QString contents = stream.readAll();
        scriptFile.close();
        QJSEngine myEngine;
        myEngine.installExtensions(QJSEngine::AllExtensions);
        qDebug()<<contents;
        QJSValue result = myEngine.evaluate(contents, fileName);
        if (result.isError())
            qDebug()
                    << "Uncaught exception at line:"
                    << result.property("lineNumber").toInt()
                    << endl << result.toString();
        qDebug()<<"end";
        return a.exec();
    }
    
    

    test.jsm

    import { sum } from "./math.mjs";
    export function addTwice(left, right)
    {
        return sum(left, right) * 2;
    }
    print(sum(1,2));
    

    error

    Uncaught exception at line: 1
    "SyntaxError: Unexpected token `import'"
    
    1 Reply Last reply
    0
    • C Offline
      C Offline
      CKurdu
      wrote on 9 Oct 2019, 16:47 last edited by CKurdu 10 Sept 2019, 16:47
      #2

      Hi UremSetp

      When you write a module, you should use myEngine.importModule. So it can parse "import" and "export" keywords to use.

      QCoreApplication a(argc, argv);
      
          QString fileName = ":/test.jsm";
          QFile scriptFile(fileName);
          if (!scriptFile.open(QIODevice::ReadOnly)){
              // handle error
              qDebug()<<"open file fail!";
              return 0;
          }
          QTextStream stream(&scriptFile);
          QString contents = stream.readAll();
          scriptFile.close();
          QJSEngine myEngine;
          myEngine.installExtensions(QJSEngine::AllExtensions);
          qDebug()<<contents;
          QJSValue module = myEngine.importModule(":/test.jsm");
          QJSValue sumFunction = module.property("addTwice");
          QJSValueList list;
          list.append(3);
          list.append(4);
          QJSValue result = sumFunction.call(list);
          qDebug()<<result.toInt()<<endl;
      
      

      You reap what you sow it

      U 1 Reply Last reply 10 Oct 2019, 00:37
      1
      • C CKurdu
        9 Oct 2019, 16:47

        Hi UremSetp

        When you write a module, you should use myEngine.importModule. So it can parse "import" and "export" keywords to use.

        QCoreApplication a(argc, argv);
        
            QString fileName = ":/test.jsm";
            QFile scriptFile(fileName);
            if (!scriptFile.open(QIODevice::ReadOnly)){
                // handle error
                qDebug()<<"open file fail!";
                return 0;
            }
            QTextStream stream(&scriptFile);
            QString contents = stream.readAll();
            scriptFile.close();
            QJSEngine myEngine;
            myEngine.installExtensions(QJSEngine::AllExtensions);
            qDebug()<<contents;
            QJSValue module = myEngine.importModule(":/test.jsm");
            QJSValue sumFunction = module.property("addTwice");
            QJSValueList list;
            list.append(3);
            list.append(4);
            QJSValue result = sumFunction.call(list);
            qDebug()<<result.toInt()<<endl;
        
        
        U Offline
        U Offline
        UremSept
        wrote on 10 Oct 2019, 00:37 last edited by
        #3

        @CKurdu

        Thank you! I have been able to implement the features I want, but it is not too beautiful.Is there a better way?
        main.cpp

        int main(int argc, char *argv[])
        {
            QCoreApplication a(argc, argv);
        
            QString fileName = "./test.jst";
            QFile scriptFile(fileName);
            if (!scriptFile.open(QIODevice::ReadOnly)){
                qDebug()<<"open file fail!";
                return 0;
            }
            QTextStream stream(&scriptFile);
            QString contents = stream.readAll();
            scriptFile.close();
            QJSEngine myEngine;
            myEngine.installExtensions(QJSEngine::AllExtensions);
            QJSValue module = myEngine.importModule("./test.jsm");//The first js file needs to be imported like this and cannot be imported in the script.
            myEngine.globalObject().setProperty(QLatin1String("_import"),module);
            QJSValue result = myEngine.evaluate(contents, fileName);
            if (result.isError())
                qDebug()
                        << "Uncaught exception at line:"
                        << result.property("lineNumber").toInt()
                        << endl << result.toString();
            qDebug()<<"end";
            return a.exec();
        }
        

        first js :test.jst

        print(_import.addTwice(1,2));
        

        first module:test.jsm

        import { sum } from "./math.mjs";
        export function addTwice(left, right)
        {
            return sum(left, right) * 2;
        }
        

        other module:

        export function sum(left, right)
        {
            return left + right
        }
        
        1 Reply Last reply
        0
        • C Offline
          C Offline
          CKurdu
          wrote on 10 Oct 2019, 10:41 last edited by CKurdu 10 Oct 2019, 10:42
          #4

          @UremSept said in QJsEngine cannot use import syntax:

          Thank you! I have been able to implement the features I want, but it is not too beautiful.Is there a better way?

          You are welcome. What is your final aim? I think you want to make a library consists of modules and a final main script that uses all of the libraries. But QJsEngine is made for QML apps and for this reason it maybe not a good solution as node.js (You can use es6-7 well-supported environment).

          To beautify the work, you can create a method dynamically list files in a directory and install all modules that your start script requires.

          You reap what you sow it

          U 1 Reply Last reply 10 Oct 2019, 11:19
          1
          • C CKurdu
            10 Oct 2019, 10:41

            @UremSept said in QJsEngine cannot use import syntax:

            Thank you! I have been able to implement the features I want, but it is not too beautiful.Is there a better way?

            You are welcome. What is your final aim? I think you want to make a library consists of modules and a final main script that uses all of the libraries. But QJsEngine is made for QML apps and for this reason it maybe not a good solution as node.js (You can use es6-7 well-supported environment).

            To beautify the work, you can create a method dynamically list files in a directory and install all modules that your start script requires.

            U Offline
            U Offline
            UremSept
            wrote on 10 Oct 2019, 11:19 last edited by
            #5

            @CKurdu I just want to customize some APIs in C++ and then use them easily in scripts. Thank you for your suggestion, these are enough to use.

            1 Reply Last reply
            0
            • C Offline
              C Offline
              CKurdu
              wrote on 10 Oct 2019, 12:04 last edited by CKurdu 10 Oct 2019, 12:06
              #6

              @UremSept said in QJsEngine cannot use import syntax:

              I just want to customize some APIs in C++ and then use them easily in scripts. Thank you for your suggestion, these are enough to use.

              Then If you want to use this script files without "import" restriction you can do it like below.
              First Create a main.qml in working directory file where it isn't in a resource file.

              import "./test.mjs" as TestImport //You can import start script module here
              import QtQuick 2.0
              QtObject{
                  id:root
                  Component.onCompleted: {
                      var result = TestImport.addTwice(2,4); 
                      console.log(result);
                  }
              }
              

              Your test.mjs file in working directory.

              import { sum } from "./math.mjs";
              export function addTwice(left, right)
              {
                  return sum(left, right) * 2;
              } 
              

              Your math.mjs file in wokring directory

              export function sum(left, right)
              {
                  return left + right
              } 
              
              

              And your main.cpp file

              #include <QCoreApplication>
              #include <QQmlApplicationEngine>
              #include <QFile>
              #include <QTextStream>
              #include <QJSEngine>
              #include <QDebug>
              #include <QQmlEngine>
              #include <QObject>
              
              int main(int argc, char *argv[])
              {
                  QCoreApplication a(argc, argv);
                  QQmlApplicationEngine myEngine("main.qml");
                  return a.exec();
              }
              

              This is actually console application and when you use QQmlApplicationEngine you can faciliate many qt imports also.

              You reap what you sow it

              U 1 Reply Last reply 11 Oct 2019, 08:15
              1
              • C CKurdu
                10 Oct 2019, 12:04

                @UremSept said in QJsEngine cannot use import syntax:

                I just want to customize some APIs in C++ and then use them easily in scripts. Thank you for your suggestion, these are enough to use.

                Then If you want to use this script files without "import" restriction you can do it like below.
                First Create a main.qml in working directory file where it isn't in a resource file.

                import "./test.mjs" as TestImport //You can import start script module here
                import QtQuick 2.0
                QtObject{
                    id:root
                    Component.onCompleted: {
                        var result = TestImport.addTwice(2,4); 
                        console.log(result);
                    }
                }
                

                Your test.mjs file in working directory.

                import { sum } from "./math.mjs";
                export function addTwice(left, right)
                {
                    return sum(left, right) * 2;
                } 
                

                Your math.mjs file in wokring directory

                export function sum(left, right)
                {
                    return left + right
                } 
                
                

                And your main.cpp file

                #include <QCoreApplication>
                #include <QQmlApplicationEngine>
                #include <QFile>
                #include <QTextStream>
                #include <QJSEngine>
                #include <QDebug>
                #include <QQmlEngine>
                #include <QObject>
                
                int main(int argc, char *argv[])
                {
                    QCoreApplication a(argc, argv);
                    QQmlApplicationEngine myEngine("main.qml");
                    return a.exec();
                }
                

                This is actually console application and when you use QQmlApplicationEngine you can faciliate many qt imports also.

                U Offline
                U Offline
                UremSept
                wrote on 11 Oct 2019, 08:15 last edited by
                #7

                @CKurdu Thank you very much, I don’t know enough, this solves my problem.

                1 Reply Last reply
                0

                3/7

                10 Oct 2019, 00:37

                • Login

                • Login or register to search.
                3 out of 7
                • First post
                  3/7
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • Users
                • Groups
                • Search
                • Get Qt Extensions
                • Unsolved