In package.json
, I usually use a postversion
hook to publish to npm. Here we want to do the same thing, but we need to use a secret key because this is a private package.
In the repo's .env
file, add the secret key. This file is ignored in git
.
NPM_TOKEN="ghp_xxxxx"
In .npmrc
, read the secret:
//npm.pkg.github.com/:_authToken=${NPM_TOKEN}
Expand the .env
file in the npm pubish
command:
{
"scripts": {
"postversion": "git push && git push --tags && export $(cat .env | xargs) && npm publish",
}
For the server (for installing dependencies) we want a token with read permissions only. Use this when installing dependencies
"scripts": {
"preinstall": "export $(cat .env | xargs)",
}
In github, create an access token, then add it to the local .env
file.
to use the public registry for install:
npm i <pkg name> --@my-scope:registry=https://registry.npmjs.org/
{
"scripts": {
"postversion": "git push && git push --tags && npm run pub,
"pub": "npm publish && export $(cat .env | xargs) && npm publish --@my-scope:registry=https://registry.npmjs.org/""
}
}
This is assuming that the 'default' publish target is configured in publishConcifg
{
"publishConfig": {
"registry": "https://npm.pkg.github.com"
},
}
{
"preinstall": "export $(cat .env | xargs)",
}
And in .npmrc
@my-scope:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${NPM_TOKEN}
to list dependencies:
npm ls --omit=dev --depth=0
to return a count of dependencies:
expr $(npm ls --omit=dev --depth=0 | wc -l) - 2
- 2
is for two lines that are automatically added to the output
Build & publish the code, without duplicating code in git
:
"scripts": {
"test": "standard index.js",
"pub": "npm pub && npm publish --registry https://npm.pkg.github.com",
"build": "esbuild index.js --outfile=dist/index.cjs --platform=node --format=cjs",
"prepublishOnly": "npm run build"
},
Use this hook to build some source code into a distributable version when you publish to npm.
Ignore the compiled files in git .gitignore
:
dist/*
Create a file .npmignore
, and tell it not to ignore the compiled files:
!dist/*
npm i -D some-package --legacy-peer-deps