NPM Packaging - Publishing to Github
Github Packages gives you registries for commonly used packages, such as Node(npm), Docker, RubyGems, Apache Maven, Gradle
In this post, we'll explore how to publish node packages using npm
to Github and how to consume npm
packages from Github.
Let's start with writing a very simple node package
- Create a github repo
my-node-package
(or whatever name you prefer 😉) - Clone the repo and add your main JS file there
git clone git@github.com:<SCOPE>/my-node-package.git && cd my-node-package touch index.js
- [Important]
<SCOPE>
should be replaced by your github username or organization name. - Add code for your package. In my case, my package will simply return
You have succesfull installed and ran lionbridgeai's rei package
. So, theindex.js
file would look likemodule.exports = function rei() { return "You have succesfull installed and ran lionbridgeai's rei package"; };
- Let's add a
package.json
file. This is the only required file for a package.
Here{ "name": "@<SCOPE>/my-node-package", "version": "1.0.0", "description": "This is an example node package", "repository": "https://github.com/<SCOPE>/my-node-package", "main": "index.js", "publishConfig": { "registry": "https://npm.pkg.github.com" } }
name
is scoped package name.version
is package's version in semantic notation.repository
is the github repo you created inStep 1
, if your repo isprivate
your package would be private otherwise your package will be public.main
is the entrypoint for the package, in our case it'sindex.js
file and finallypublishConfig
would tell the npm about the target registry for publishing. - That's it. We have written our example package. In next section, we'll see how to publish it.
Publishing the package
- Create a PAT(personal access token) from Github with
repo
andwrite:packages
permissions - Do npm login using your github username as username and personal access token as password.
npm login --scope=@<SCOPE> --registry=https://npm.pkg.github.com
- voilà ! We are ready to publish
# update your package's major, minor or patch version npm version major # publish it npm publish
Installing package from Github
- As we did in last section, login to github packages(required if installing a private package). And append the following config for github registry in your npmrc file
Remember the scope? It's github org or user id.@<SCOPE>:registry=https://npm.pkg.github.com
- That's it! Run
npm install <package-name>
to install
If you are interested, join me in part 2, where we'll explore how to add unit tests for our package and to make use of github actions to automatically run tests and publish
Â