1.0.1 • Published 11 months ago
@c_dzivkovic/hello-world-package v1.0.1
Publishing Your First NPM Package to a Private GitHub Repository
Create a "Hello World" Package
Step 1: Create a Private GitHub Repository
- Log in to GitHub.
- Create a new repository (e.g.
hello-world-package
). - Set the repository to Private.
- Click "Create repository."
Step 2: Initialize Git in Your Project
In your local project directory, run the following commands:
git init git remote add origin https://github.com/dzivkovi/hello-world-package.git git add . git commit -m "Initial commit" git push -u origin master
Step 3: Configure NPM for GitHub Packages
Create
.npmrc
: Add the following to your project's.npmrc
file:@c_dzivkovic:registry=https://npm.pkg.github.com //npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}
- Replace
c_dzivkovic
with your GitHub username. Set your GitHub PAT as an environment variable:
export GITHUB_TOKEN=ghp_YourGitHubToken
- Replace
Log in to GitHub Packages: Use the following command to authenticate with GitHub Packages:
npm login --registry=https://npm.pkg.github.com
- You will be prompted for your GitHub username, email, and a Personal Access Token (PAT) that you previously generated with
write:packages
andread:packages
scopes.
- You will be prompted for your GitHub username, email, and a Personal Access Token (PAT) that you previously generated with
Publish to GitHub Packages: Run the following command to publish your package:
npm publish
Step 4: Create Unit Tests
Install Mocha:
npm install --save-dev mocha
Create Test File: Add
test/index.test.js
with the following content:const os = require('os'); const assert = require('assert'); const helloWorld = require('../index'); describe('HelloWorld Function', function () { it('should print "Hello, world!"', function () { let output = ''; const storeLog = inputs => (output += inputs); console.log = storeLog; helloWorld(); assert.strictEqual(output, `Hello, world!${os.EOL}`); }); });
Update
package.json
: Add a test script in thescripts
section:"scripts": { "test": "mocha" }
Testing: Run unit tests in the main project:
npm test
Consume a "Hello World" Package
Create Client Subfolder:
mkdir client cd client
Initialize NPM Project:
npm init -y
Configure
.npmrc
for Client: Add the same.npmrc
configuration with your GitHub PAT:@c_dzivkovic:registry=https://npm.pkg.github.com //npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}
Install Package:
npm install @c_dzivkovic/hello-world-package
Create Client File:
const helloWorld = require('@c_dzivkovic/hello-world-package'); helloWorld();
Run the client file in the
client
subfolder:node client.js