Index
Overview


Modules are basically Javascript files.

E.g. you may have coded circle.js - this file can be a module.

You can load (require) these modules (files) into another module.

Coding and Using a Module


circle.js has been coded as shown.

The key line is the exports line.

circle.js is a module.
//shapes/circle.js

class Circle {
	//code here
}

exports.Circle = Circle
circle-user.js has been coded as shown.

The 'circle' module is imported as shown.
//circle-user.js

const
	{Circle} = require('shapes/circle');

//Class Circle is now available for use using normal js code.


Coding a Package


You first setup a package.json file something like that shown.

In this discussion we are most interested in the lines highlighted which indicate:

  • The name of the package
  • The entry point of the package
  • The entry point of the package
{
  
1
"name": "@ashafoo/shapes", "version": "1.0.0", "description": "Sample", "keywords": ["package sample", "basic sample"], "homepage": "https://github.com/asha-foo/shapes#readme",
2
"main": "index.js",
3
"module": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/asha-foo/shapes.git" }, "author": "af", "license": "ISC", "private": false, "devDependencies": {}, "directories": { "test": "test" }, "bugs": { "url": "https://github.com/asha-foo/shapes/issues" } }
//index.js

1
//Importing const {Circle} = require('./shapes/Circle.js'), {Rectangle} = require('./shapes/Rectangle.js'), {RectangleSet} = require('./shapes/RectangleSet.js');
2
//Exporting exports.Circle = Circle; exports.Rectangle = Rectangle; exports.RectangleSet = RectangleSet;


Using a Package


Create a new consumer project and add the dependency highlighted here.

This will consume from the npm public library.

To test locally, you may also use a "npm links" approach.

Note: if testing locally, you could use a npm links approach.
dependencies": {
    "@ashafoo/shapes": "^1.0.0
Now, in your CLI, in the project root directory, you want to run the command shown.
# using package.json
> npm install

# alternatively
# explicit (will update package.json for you)
> npm install @ashafoo/shapes
To import the desired sub-modules, you use the highlited require statement.
//my-test.js

const {Rectangle, Circle, RectangleSet} = require('@ashafoo/shapes');