Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Creating single node module to access multiple extended classes in separate files authored in coffeescript

Creating single node module to access multiple extended classes in separate files authored in coffeescript

Problem

I'd like to create a single node library that includes multiple classes, each authored using coffee-script in a different file and extending from one another. For instance, say I have the following files in node_modules/mymodule/src:

File 1:

  class Base
    constructor: (@foo) ->

  module.exports = Base

File 2:

  Base = require './Base.coffee'

  class Derived extends Base
    constructor: (@bar) ->
      super

  module.exports = Derived

File 3:

  Base = require './Base.coffee'

  class Derived2 extends Base
    constructor: (@baz) ->
      super

  module.exports = Derived2

Is there some way I can bind these 3 classes in such a way so that I can define "mymodule" in package.json file and then access the module and its classes like so?

File using mymodule:

  my module = require 'mymodule'

  Base = new mymodule.Base
  Derived = new my module.Derived
  Derived2 = new my module.Derived2
  #Do stuff

I don't know what to do in package.json to make this happen, and I can't find documentation on this anywhere. Is this possible?

Problem courtesy of: Clandestine

Solution

You can use main to configure the entry point you your module and expose your classes there. (I haven't done this with coffee-script).

The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.

This should be a module ID relative to the root of your package folder.

Configure your main to point at index.js or similar. Your index.js would then look something like this:

module.exports.Base     = require('./pathtobase/Base.coffee');
module.exports.Derived  = require('./pathtobase/Derived.coffee');
module.exports.Derived2 = require('./pathtobase/Derived2.coffee');
Solution courtesy of: dc5

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Creating single node module to access multiple extended classes in separate files authored in coffeescript

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×