Coder Social home page Coder Social logo

npm-module-starter's Introduction

Npm module starter

Skeleton for creating a npm module

Module commands

  • npm run test: runs all tests in __tests__
  • npm run demo: runs the demo in demo/demo.helpers-file-create.js
  • your-namespace--module-name--core-dummy -m 'I am a message!' (after running npm link): runs the globally available clt in bin/bin.core-dummy.js

Don‘t forget to change your-namspace and module-name!

3rd Party Modules

  • jest for unit testing
  • mkdirp for recursive directoy creation
  • yargs for interactive cli building

Files and folders

  • __tests__
    • jest.core-dummy.js
  • bin
    • bin.core-dummy.js
  • demo
    • demo.helpers-file-create.js
  • lib
    • helpers
      • helpers-file.js
      • index.js
    • tpl
      • .gitignore
      • .htaccess
    • core.js
    • index.js
  • .gitignore
  • index.js
  • LICENSE
  • package.json
  • README.md

Code excerpts

package.json

{
  "name": "@your-namespace/module-name",
  "version": "1.0.0",
  "description": "your module description",
  "main": "index.js",
  "bin": {
    "your-namespace--module-name--core-dummy": "bin/bin.core-dummy.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/username/repo-name.git"
  },
  "scripts": {
    "test": "jest",
    "demo": "rm -rf demo/created && node demo/demo.helpers-file-create.js"
  },
  "license": "SEE LICENSE IN LICENSE",
  "dependencies": {
    "mkdirp": "^0.5.1",
    "yargs": "^4.3.2"
  },
  "devDependencies": {
    "jest-cli": "^0.9.2"
  }
}

LICENSE

SEE: http://sid.mit-license.org/

Hosted MIT License with details controlled through this repo http://mit-license.org. More info here.

index.js

// Example code
var pkg = require('./package.json');

function getProp(obj, prop) {
    return obj[prop];
}

var jestCli = getProp(pkg.devDependencies, 'jest-cli');

console.log('This package requires jest-cli ' + jestCli);

lib/helpers/helpers-file.js

// File helper functions
module.exports = {
    create: function (dest, content, cb) {
        // Core modules
        var fs   = fs || require('fs');
        var path = path || require('path');
        // 3rd party modules
        var mkdirp = mkdirp || require('mkdirp');

        mkdirp(path.dirname(dest), function (err, data) {
            if (err) {
                cb(true, err);
            }

            fs.writeFile(dest, content, function (err, data) {
                if (!err) {
                    cb(false, data);
                } else {
                    cb(true, err);
                }
            });
        });
    },

    getContent: function(file, cb) {
        // Core modules
        var fs = fs || require('fs');

        fs.readFile(file, {encoding: 'utf-8'}, function (err, data) {
            if (!err) {
                cb(false, data);
            } else {
                cb(true, err);
            }
        });
    },

    exists: function (file, cb) {
        // Core modules
        var fs = fs || require('fs');

        fs.stat(file, function (err, stat) {
            if (err === null) {
                cb(false, stat);
            } else if (err.code === 'ENOENT') {
                cb(new Error('File not found: ' + err));
            } else {
                cb(true, err);
            }
        });
    },

    getPaths: function (dir, options) {
        // Core modules
        var fs   = fs || require('fs');
        var path = path || require('path');

        // Set default options
        var o = {
            exts: [],
            paths: [],
            recursive: true
        }
        // Feed user configuration options
        if ('undefined' !== typeof options) {
            for (var i in options) {
                if ('undefined' !== typeof options[i]) {
                    o[i] = options[i];
                }
            }
        }

        fs.readdirSync(dir).forEach(function (file) {
            if (fs.statSync(dir + '/' + file).isDirectory()) {
                if (o.recursive) {
                    o.paths = module.exports.getFilePaths(dir + '/' + file, options);
                }
            } else {
                if (o.exts.length > 0) {
                    var ext = path.extname(file).replace('.', '');
                    if (o.exts.indexOf(ext) > -1) {
                        o.paths.push(path.join(dir, file));
                    }
                } else {
                    o.paths.push(path.join(dir, file));
                }
            }
        });

        return o.paths;
    }
};

lib/core.js

module.exports = {
    dummy: function (message) {
        var message = message || 'I am the default message!';

        return message;
    }
};

lib/index.js

// Shortcut for bulk export
'use strict';

exports.core = require('./core.js');

demo/demo.helpers-file-create.js

'use strict';

// Core modules
var path = require('path');

// Custom modules
var helpersFile = require('../lib/helpers').helpersFile;

var customTplPaths = [];

var tpl = helpersFile.getPaths(path.join(__dirname, '../lib/tpl'), {
    exts: [],
    paths: customTplPaths,
    recursive: true
});

tpl.forEach(function (file) {
    var dir  = path.join(__dirname, 'created');
    var dest = path.join(dir, path.basename(file));

    helpersFile.getContent(file, function onComplete(err, data) {
        if (!err) {
            var content = data;

            helpersFile.create(dest, content, function onComplete(err, data) {
                if (!err) {
                    console.log(content);
                } else {
                    console.error(err);
                }
            });
        } else {
            console.error(err);
        }
    });
});

bin/bin.core-dummy.js

#! /usr/bin/env node

// 3rd party modules
var argv = require('yargs')
    .usage('Usage: -bash <command> [options]')
    .option('message', {
        type: 'string',
        alias: 'm',
        describe: 'Provide your message.'
    })
    .example("-bash --message 'It works!'", 'It works!')
    .help('help')
    .alias('help', 'h')
    .argv;

// Custom modules
var core = require('../lib/core.js');

// Set message
var message = argv.message || false;

// Output message
console.log(core.dummy(message));

__tests__/jest.core-dummy.js

// Tell jest that it should always return the real module specified in require
jest.unmock('../lib/core.js');

// Describe test
describe('core.dummy', () => {
    it('returns given string', () => {
        const core = require('../lib/core.js');

        expect(core.dummy('It works!')).toBe('It works!');
    });
});

npm-module-starter's People

Contributors

sidisinsane avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.