Private NPM packages on GitHub

Posted Thursday, January 7, 2021.

After creating a component library, you might want to host it on a private GitHub repo as a package.

Code Changes

First, to adjust which repo and registry it gets published to, change your package.json file (change personal details):

{
...,
"repository": {
"type": "git",
"url": "git://github.com/hiimtmac/component-kit.git"
},
...,
"publishConfig": {
"registry": "https://npm.pkg.github.com/"
},
...
}

GitHub Setup

  1. Go to github.com
  2. Select settings and go to Developer Settings > Personal access tokens
  3. Generate a new token with the following top level scopes: repo, write:packages, delete:packages
  4. Name it something which you will remember what it is for and copy the token value
  5. Run npm login --registry=https://npm.pkg.github.com and follow the prompts
  6. Authentication details will be then stored in ~/.npmrc

Publish

Now that you have access to publish to private repos, you can publish the files in the /dist folder. Run:

yarn publish

Make sure to have run yarn build and set the correct package version before running the publish step.

Consuming Package

You will need to have the repository config setup so that npm knows where to fetch the package from.

To do this, edit your ~/.npmrc file and append the contents to the bottom (changing to your username or organization's username):

//npm.pkg.github.com/:_authToken=some_token_here
...
@hiimtmac:registry=https://npm.pkg.github.com
...

You can have as many mappings in there as you need for different organizations (provided your token works for all of them). Now you can pull and add the package to you project:

yarn add @hiimtmac/component-library

In Closing

In a future post, I will detail how to adjust this project to use a private github repo as the npm repo, and how to pull from it in projects.


Tagged With: