Thursday, 18 May 2017

Are JavaScript classes acceptable Node modules?

Bear with me as I lead you through the process that elicited my question.

I'm working on a CLI app in node and I'm using objects to encapsulate my business logic using this pattern:

// my-project/lib/widget/myobject.js

var MyObject = function(x) {
  this.x = x;
};

MyObject.prototype.getX = function() {
  return this.x;
};

module.exports = MyObject;

I'm also testing these objects:

// my-project/test/lib/widget/myobject.spec.js

var MyObject = require('../../../lib/widget/myobject.js');

describe('MyObject', function() {
  ...
});

At one point I was unhappy with the naming and directory structure I had chosen. I found myself tediously counting those parent directory references (..) in several spec files when rewriting the relative paths. I figured there must be an easier way to reference a root directory containing these object definitions.

One of the recommendations I found here suggested "putting application-specific modules into node_modules".

Now, as I understand modules, they are the packages I download from npm and use in my project. They contain libraries of useful things with a single API exported to me when I call require. This is not how I view the simple single-purpose classes built specifically for the internal use of my application.

If you've stuck with me this far, thank you! Here is my question:

How do I make the internals of my application more "modular" so it properly follows the intent of the Node module system while remaining object oriented?



via jkeeler

No comments:

Post a Comment