When using a private GitHub repository as an npm dependency, follow these steps:
1. Create and Configure the Private Repository
- First, create a new private repository on GitHub.
- Ensure your repository contains a valid
package.jsonfile that specifies your project name, version, and other necessary information.
2. Add the Dependency to Your Project
- In your project's
package.jsonfile, you can directly add the dependency using the GitHub repository URL. The format is:
Alternatively, you can use specific tags or branches:json"dependencies": { "your-private-package": "git+https://github.com/yourusername/your-private-repo.git" }json"dependencies": { "your-private-package": "github:yourusername/your-private-repo#branch-name" }
3. Configure Access Permissions
- Since the repository is private, configure appropriate permissions to allow npm to fetch the code. The most common method is to use a Personal Access Token (PAT).
- Generate a PAT on GitHub and ensure it has sufficient permissions to access the private repository.
- Use this token for authentication. You can set the environment variable in your terminal or CI/CD system:
Then, add the following configuration to yourbashexport NPM_TOKEN="your-personal-access-token".npmrcfile:plaintext//npm.pkg.github.com/:_authToken=${NPM_TOKEN}
4. Install the Dependency
- After configuration, you can run the
npm installcommand to install the package from the private repository, just like installing any other npm package.
Real-World Example
For example, I was involved in a project where we needed to use a custom encryption algorithm developed by our internal team, which was managed as an npm package in a private GitHub repository. Following the above steps, we first ensured all developers could securely access the library by configuring the PAT, and then used it by specifying the dependency in the project's package.json. This way, whenever someone runs npm install, the private package is installed, ensuring a smooth development workflow.
The advantage of this method is that it ensures the confidentiality and security of the code while leveraging npm's package management capabilities to simplify dependency management and deployment.