Creating a sample JavaScript package

In my previous post I covered some steps to use yalc to create local packages. Let’s look at creating a very simple package.

We’ll create a simple little mathematics package which will include functions to add, subtract, divide and multiply.

  • Create a folder for our package, for example Math
  • Add an index.js file which should look like this
    'use strict';
    
    module.exports = {
        add,
        subtract,
        divide,
        multiply
    }
    
    function add(a, b) {
        return a + b;
    }
    
    function subtract(a, b) {
        return a - b;
    }
    
    function divide(a, b) {
        return a / b;
    }
    
    function multiply(a, b) {
        return a * b;
    }
    
  • Now, as we’re going to want to turn this into a package, run
    yarn init --yes
    
  • Edit the package.json file to look like this
    {
      "name": "Math",
      "version": "1.0.0",
      "license": "MIT",
      "private": true
    }
    

Let’s look at what we’ve done, the use of index.js as opposed to say Mathmatics.js is this will then make referencing the file much simpler within the code importing the file, for example we can import like this

import Math from 'Math';

var result = Math.add(2, 5);

We’ve used strict mode to restrict the some JavaScript features but also enhances prevention of silly mistakes.

Next we need to export (at the module level) our functions. In the example we export multiple functions. We could also use the following syntax

module.exports = {
   add: function(a, b) 
   {
      return a + b;
   },
   subtract: function(a, b) 
   {
      return a - b;
   }
   // etc.
}

Another alternative syntax is

exports.add = function(a, b) {
   return a + b;
}

exports.subtract = function(a, b) {
   return a - b;
}
// etc.

Now you can package this up using yalc (as per my previous post on yalc).