mnaoumov / obsidian-fix-require-modules

An Obsidian plugin that fixes require() calls, supporting JavaScript and TypeScript modules, enabling easy invocation, and adding code buttons for enhanced scripting capabilities.
MIT License
11 stars 0 forks source link

Error:MyClass is not a constructor #2

Closed louismax0815 closed 4 days ago

louismax0815 commented 3 weeks ago

Hello, I am a beginner of Javascript. But I really want to use some scripts to customize the experience of Obsidian. So I am learning to create my own dummy :) scripts with some plugins like this one. But I have trouble when I am trying to import modules inside dataviewjs block.

Here is the JS file:

// test.js
class MyClass {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}!`);
  }
}
module.exports = MyClass;

Here is the dataviewjs content:

const MyClass = require("/_Scripts/JS/Modules/test.js"); const myObject = new MyClass('World'); myObject.greet();

I got an error in the editor under the reading view:

Evaluation Error: TypeError: MyClass is not a constructor at eval (eval at (plugin:dataview), :2:18) at DataviewInlineApi.eval (plugin:dataview:18885:16) at evalInContext (plugin:dataview:18886:7) at asyncEvalInContext (plugin:dataview:18896:32) at DataviewJSRenderer.render (plugin:dataview:18922:19) at DataviewJSRenderer.onload (plugin:dataview:18464:14) at e.load (app://obsidian.md/app.js:1:1166456) at DataviewApi.executeJs (plugin:dataview:19465:18) at DataviewPlugin.dataviewjs (plugin:dataview:20386:18) at eval (plugin:dataview:20264:124)

Could you plz tell me what I did wrong?Thanks!!!

louismax0815 commented 3 weeks ago

Just to clarify, I also used the Modules plugin. So I think the cause of this error is that my export might not be appropriate. But I really don`t know how to combine this plugin with the Modules and dataviewjs to make importing of modules works.

mnaoumov commented 4 days ago

@louismax0815

Could not reproduce.

Try

const MyClass = require("/_Scripts/JS/Modules/test.js");
console.log(MyClass);

and see what is returns.

MyClass is not a constructor is a weird error, we need to understand what the object is.

louismax0815 commented 4 days ago

I modified my dataviewjs code with this: const{MyClass} = require("/_Scripts/JS/Modules/test.js");

Brace added and It works. Thanks!

mnaoumov commented 4 days ago

@louismax0815 I assume Modules plugin wraps your code in extra object, that's why you had to deconstruct desired property via { ... } approach. I tested your code without Modules and it worked as expected