Piranha Piranha - 5 months ago 23
Node.js Question

node 5 es6 export import class

This seems to be a simple problem, but the answers internet is cluttered with es5, babel, typescript, or legacy node 4 questions.

Question: How to export this:

**server.js**
class Server {

constructor(port) {
this._port = port;
}

start() {
// Some code here.
}

stop() {
// Some code here.
}
}


To use it app.js exactly like this:

**app.js**
var Server = require("server");

var server = new Server(80);
server.start();


Pure Node 5 with ES6, no babel, or additional node packages. Just this.

Answer

You can export the class:

module.exports = Server;

And, if server.js is located in the same directory as app.js, you should use a relative path for require(), too:

// app.js
var Server = require("./server");
...