Since npm
is a part of Github now, you can publish an npm package with Github. Let’s learn how to do that in this blog.
Step 1: Create a Personal Access Token
Create a personal access token from Github settings

Step: 2 Create a .npmrc file
Create a new ~/.npmrc file if one doesn’t exist, and add the following replacing TOKEN with your personal access token that you created above.
//npm.pkg.github.com/:_authToken=TOKEN
Step 3: Authenticate through terminal
To authenticate by logging in to npm, use the npm login
command, replacing USERNAME with your GitHub username, TOKEN with your personal access token, and PUBLIC-EMAIL-ADDRESS with your email address. So run this in terminal
$ npm login --registry=https://npm.pkg.github.com
> Username: USERNAME // npm username
> Password: TOKEN // token you generated above.
> Email: PUBLIC-EMAIL-ADDRESS // email address registered with https://www.npmjs.com/
Step 4: Scope mapping
You can set up the scope mapping for your project using either a local ~/.npmrc file in the project or using the publishConfig
option in the package.json.
Make sure to following only way out of the two:
a- Method one: Using local .npmrc
In the same directory as your package.json
file, create or edit an .npmrc
file to include a line specifying GitHub Packages URL and the account owner. Replace OWNER
with the name of the user or organization account that owns the repository containing your project.
registry=https://npm.pkg.github.com/OWNER
b. Using publishConfig in package.json
Edit the package.json file for your package and include a publishConfig
entry.
"publishConfig": {
"registry":"https://npm.pkg.github.com"
}
Now the below steps with be the same for either options you choose from the one’s demonstrated above.
Prefix the owner name in the package.json, Replace @ownername with name of the user or organization account that owns the repository containing your project. and package-name
with your npm package name that you want to publish
"name": "@ownername/package-name",
Also add the repository in package.json
with following information. Replace the the ownername
and package-name
with yours.
"repository": {
"type": "git",
"url": "git+https://github.com/ownername/package-name.git"
},
Last step is to run npm publish
from the root of your repository where your package.json exists.
npm publish

Here is an example of a package published via npm

If you would also like to publish the package to npmjs.org then you can run below command from the root of your project where you have package.json
npm publish --registry=https://registry.npmjs.org
You can also use the flag --access public
for public packages and --scope=@my-username
for private package.
You can find more information here