简体   繁体   中英

How to create a npm package with a method attached to the object?

I am trying to create a npm package of that could be required like this:

var Greeks = require('greek-mythology-data');
var gods = new Greeks('gods');
gods.sortByName();

but I have only managed to do something like this :

var Greeks = require('greek-mythology-data');
var gods = require('greek-mythology-data/data/gods.json');
gods = new Greeks(gods);
console.log(gods.sortByName());

so far I have this

var all = require('./data/greeks.json');
var demigods = require('./data/demigods.json');
var generalDeities = require('./data/general-deities.json');
var giants = require('./data/giants.json');
var gods = require('./data/gods.json');
var kings = require('./data/kings.json');
var primordialDeities = require('./data/general-deities.json');
var seaDeities = require('./data/sea-deities.json');
var titans = require('./data/titans.json');

function Greeks(collection) {
  this.collection = collection;

 /* return {
    all: all,
    demigods: demigods,
    generalDeities: generalDeities,
    giants: giants,
    gods: gods,
    kings: kings,
    primordialDeities: primordialDeities,
    seaDeities: seaDeities,
    titans: titans,
  }*/
}

Greeks.prototype.sortByName = function() {
  var compare = function(a, b) {
    if (a.name < b.name)
      return -1;
    if (a.name > b.name)
      return 1;
    return 0;
  };

  return this.collection.sort(compare);
};

module.exports = Greeks;

I dont think the solution i have right now is very convenient.

Am I taking the right approach ?

I also wrote it in es5 for compatibility but should I move it to ES6/ES2015 and use import/export and classes ?

You could use regular module.exports syntax like this in the same file you have your Greeks function.

module.exports = {
    Greeks,
    gods,
    kings
    // ... all other objects
}

And then use it like this in you main file

var GreekMyth = require('greek-mythology-data');
var gods = new GreekMyth.Greeks(GreekMyth.gods);
console.log(gods.sortByName());

The naming of things can be improved

You seem to be looking for

const collections = {
    all: all,
    demigods: demigods,
    generalDeities: generalDeities,
    giants: giants,
    gods: gods,
    kings: kings,
    primordialDeities: primordialDeities,
    seaDeities: seaDeities,
    titans: titans,
};
function Greeks(name) {
    this.collection = collections[name];
}

Although exposing the collections directly on your module interface might be a better idea than to refer to them with strings. Btw, in ES6 you should be able to simplify the above to

import * as collections from './data';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM