Lesson 03-npm Publishing and Sharing Packages

Preparation

Create an npm Account

Visit the npm official website (https://www.npmjs.com/) and register an account.

Configure npm

Set up your npm username, email, and other details in the terminal:

npm set init.author.name "Your Name"
npm set init.author.email "you@example.com"
npm set init.author.url "http://yourwebsite.com"

Creating an npm Package

Initialize a Project

mkdir my-npm-package
cd my-npm-package
npm init -y

Write Code

Create an index.js file in the project root:

module.exports = function hello(name) {
  return `Hello, ${name || 'world'}!`;
};

Add Tests

Create test/index.test.js:

const assert = require('assert');
const hello = require('../index');

describe('Hello function', () => {
  it('should greet with name', () => {
    assert.strictEqual(hello('Alice'), 'Hello, Alice!');
  });

  it('should greet with default name', () => {
    assert.strictEqual(hello(), 'Hello, world!');
  });
});

Install Testing Framework

npm install mocha chai --save-dev

Add Scripts

Edit package.json:

{
  "name": "my-npm-package",
  "version": "1.0.0",
  "description": "A simple hello world npm package.",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/yourusername/my-npm-package.git"
  },
  "keywords": [
    "hello",
    "world"
  ],
  "author": "Your Name",
  "license": "MIT",
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^8.0.1"
  }
}

Testing the Package

Run tests:

npm test

Publishing the Package

Log in to npm

npm login

Publish the Package

For the first release:

npm publish

For subsequent versions:

npm version patch # or minor/major
npm publish

To unpublish:

npm unpublish

Maintaining and Updating the Package

Update Documentation

Maintain README.md with examples and usage instructions.

Handle Issues and Pull Requests

Respond to community feedback in your GitHub repository.

Release New Versions

Update version numbers following SemVer and publish new versions.

Best Practices

Use Version Control

Manage code history with Git.

Add a License

Declare an open-source license in a LICENSE file.

Write Clear Documentation

Ensure README.md is detailed and easy to understand.

Use GitHub Pages

Create a documentation website for your package.

Monitor Dependency Security

Use npm audit to check dependency vulnerabilities.

Share your love