I create an extension class for QJSEngine that provides a function importModule() to engine's global object that works like an the standard import statement in JS.
The simplified version of this class is below.
class ModuleImportExtension : public QObject
{
Q_OBJECT
public:
ModuleImportExtension(QJSEngine* engine) : QObject(), m_engine(engine) {}
protected:
Q_INVOKABLE void import(const QString& relativePath, const QString& jsIdentifier)
{
auto moduleJsVal = m_engine->importModule(QDir::current().absoluteFilePath(relativePath));
m_engine->globalObject().setProperty(jsIdentifier, moduleJsVal);
Q_ASSERT(m_engine->globalObject().hasProperty(jsIdentifier));
}
private:
QJSEngine* m_engine;
};
To use it you need to create a QJSValue from ModuleImportExtension instance and set its import property to the engine's global object.
// ...
QJSEngine engine;
auto extObj = engine.newQObject(new ModuleImportExtension(&engine));
engine.globalObject().setProperty("importModule", extObj.property("import"));
// ...
It works well except the one case when a module code contains unknown types.
module.js
export var obj = new ccc("abcdef"); // ccc has not been declared yet
main.js
importModule("module.js", "Module");
console.log(Module.obj);
If I evaluate main.js, it would fail with message
"ReferenceError: Module is not defined"
I decided to add a Q_ASSERT in ModuleImportExtension::import and it is failed in this case. That is, the QJSValue instance of the module is not set as a property in the engine's global object. Could you please explain me why m_engine->globalObject().setProperty(jsIdentifier, moduleJsVal) does nothing?
P.S. In spite of the fact the module has unknown types, QJSEngine::importModule() doesn't return error (QJSValue::isError() is false). However, toString() of importModule() result returns
ReferenceError: ccc is not defined