0

In my ES6 Node.js application, I have a file of classes that I'm exporting:

class Class1 {...}
class Class2 {...}

module.exports = {
    Class1, Class2
}

If one day I make Class3, I don't want to have to remember to add it to the exports list. What I'd like is something like:

module.exports = {
    class Class1 {...},
    class Class2 {...}
}

Is there any syntax that accomplishes this?

1
  • You could write module.exports = { Class1: class {…}, Class2: class {…}};, but why not just use ES6 modules? Commented Aug 10, 2018 at 17:35

2 Answers 2

3

You could add the export at the same time you define the class:

module.exports.Class1 = class Class1 {...};
module.exports.Class2 = class Class2 {...};

It's not much better but may be easier to remember.

Sign up to request clarification or add additional context in comments.

2 Comments

Still have to write the class name twice, but this way I can't forget. Good enough
Outside of Node.js, in standard ES6 JavaScript, you could just say export class Class1 {...} and you wouldn't have to write the class name twice.
1

You asked for an ES6 solution: just add export before declaring your class :)

export class Foo() {

}

export class Bar() {

}

export class Baz() {

}

module.exports works fine but is CommonJs, not ES6!

In another file you can import them with the following statements:

import * as MyClasses from './path/classes.js'

const foo = new MyClasses.Foo()

or

import { Foo, Bar, Baz } from './path/classes.js'

const foo = new Foo()

1 Comment

I don't think your distinction is correct. Classes are ES6 and CommonJS + classes still counts as ES6. The question doesn't reference ES module syntax, so presumably the mention if ES6 is in reference to other common ES6 features, not specifically ES module syntax. Using ES module syntax is certainly fine in some cases, but the question also never mentions Babel, just standard Node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.