Skip to content

Instantly share code, notes, and snippets.

@AstroCB
Last active July 27, 2020 05:54
Show Gist options
  • Save AstroCB/da1c1d96b21808a5b73fea63515fae0c to your computer and use it in GitHub Desktop.
Save AstroCB/da1c1d96b21808a5b73fea63515fae0c to your computer and use it in GitHub Desktop.
This script publishes npm packages to GitHub package manager – specifically, it takes npm-distributed (through npmjs.com) packages and converts them to the required format, publishes them to the GitHub registry, and then reverts them back to their original state.
#! /usr/bin/env node
// =========== REPLACE YOUR USERNAME HERE ===========
// Must be lowercase; package will be listed as @username/package-name on GHPM
const GITHUB_USERNAME = "username";
// =========== REPLACE YOUR USERNAME HERE ===========
// Performs the changes needed to publish an npm package to GitHub package
// manager, then publishes it, then undoes those changes (to be a regular npm
// package). Assumes package.json exists in cwd.
const fs = require("fs");
const { exec } = require("child_process");
fs.readFile("package.json", (err, data) => {
if (err) return console.error("Failed to read package.json");
const info = JSON.parse(data);
const original = data.toString();
// Make ghpm changes
info.publishConfig = {
"registry": "https://npm.pkg.github.com/"
};
info.name = `@${GITHUB_USERNAME}/${info.name}`;
fs.writeFile("package.json", JSON.stringify(info), err => {
if (err) return console.error("Failed to write package.json");
exec("npm publish", (err, _, __) => {
if (err) console.error(`Failed to publish: ${err}`);
// Reset package.json file
fs.writeFile("package.json", original, err => {
if (err) console.error("Failed to write original package.json");
});
});
});
});
@AstroCB
Copy link
Author

AstroCB commented Jul 27, 2020

This script assumes that you have already authenticated with GitHub package manager using npm login or an auth token as described here.

It works by temporarily making the changes to your package.json required to publish to GitHub package manager, publishing it, and then reverting those changes so that you can publish to the global npm registry normally again.

I recommend putting this script somewhere in your PATH and binding it to a name like ghpm-publish so that you can use it in any npm-distributed repo on your machine. After that, you can do npm publish; ghpm-publish to publish to both registries at the same time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment