npm-release-package
v1.0.0
Published
A simple greeting package demonstration
Readme
Publishing an NPM Package: A Step-by-Step Guide
This repository demonstrates how to create and publish a package to the NPM registry.
Prerequisites
- Node.js installed on your machine
- An NPM account (free to create)
Step 1: Set up your project
# Create a new directory for your package
mkdir my-npm-package
cd my-npm-package
# Initialize a new npm package
npm init -yStep 2: Create your package code
Create an index.js file with your package functionality:
// index.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = { greet };Step 3: Update package.json
Edit your package.json to include necessary information:
{
"name": "your-unique-package-name",
"version": "1.0.0",
"description": "A simple greeting package",
"main": "index.js",
"keywords": ["greeting", "demo"],
"author": "Your Name",
"license": "MIT"
}Important fields:
name: Must be unique on NPM registryversion: Follow semantic versioning (major.minor.patch)main: Entry point to your packagekeywords: Help users find your package
Step 4: Add a README.md
Create a README.md file to document your package:
# Your Package Name
A simple greeting package.
## Installation
```npm install your-unique-package-name```
## Usage
```javascript
const { greet } = require('your-unique-package-name');
console.log(greet('World')); // Outputs: Hello, World!
## Step 5: Create a .gitignore file
node_modules/ .DS_Store .env
## Step 6: Create an NPM account (if you don't have one)
```bash
npm adduser
# Follow prompts to log in or create accountStep 7: Publish your package
npm publishStep 8: Updating your package
- Make your code changes
- Update the version in package.json following semantic versioning:
- Patch (1.0.0 → 1.0.1): Bug fixes
- Minor (1.0.0 → 1.1.0): New features, backward compatible
- Major (1.0.0 → 2.0.0): Breaking changes
- Run
npm publishagain
Advanced Topics
Testing your package locally
# In your package directory
npm link
# In another project directory
npm link your-package-nameCreating a .npmignore file
Similar to .gitignore, but for excluding files from your NPM package:
tests/
docs/
.github/Publishing a scoped package
Scoped packages use your username or organization name:
{
"name": "@username/package-name"
}To publish a scoped package:
# Public package
npm publish --access public
# Private package (requires paid account)
npm publishAdding tests
Consider adding tests before publishing:
# Install Jest for testing
npm install --save-dev jest
# Add test script to package.json
"scripts": {
"test": "jest"
}
# Run tests
npm test