Importing a class?

I’m a newbie to using JS in a non-browser context so please forgive me if this is a dumb question, but…

Is there a way which the JS interpreter understands to have an entire class in another file and instantiate it from within my main.js? This page talks briefly about importing values from other files, but I couldn’t figure out how to get it to work with a class declaration. I tried looking at what other extensions are doing in the code but all of the ones that are doing it that I found so far are using preprocessor/transpiler trickery (it took me a while to realize that…) and while I certainly sympathize with not wanting to write JavaScript, I’d rather avoid using such tools if possible.

Of course I’ve also tried searching but none of the answers seem to work with the interpreter in Nova.

In short, I want to do something like:

// Foo.js
class Foo {
  constructor() { }
}

// main.js
import("foo.js");
var myFoo = new Foo();

You’re on the right track.

Exporting Module Objects

Importing symbols from another file is done via the require() function. In the file to be imported, symbols can be “exported” by adding them to the module.exports object (which by default is aliased to just exports).

In your foo.js:

class MyClass {
}

exports.MyClass = MyClass;

In your main.js:

let foo = require("foo.js");
let MyClass = foo.MyClass;

let obj = new MyClass();

Replacing The Entire exports Object

By default, exports is a simple object. If you only want to export a single class, and that’s all, you can override module.exports entirely to replace the object with whatever you’d like:

In your “foo.js”:

class MyClass {
}

module.exports = MyClass

and then in your main.js:

let MyClass = require("foo.js");

let obj = new MyClass();

Thanks. I did manage to stumble across the module.exports approach last night, and since I’m used to doing the one-class-per-file approach in other languages, that’s working great for me so far. I’ll keep that other approach in mind too, though.