LoginSignup
1
0

More than 1 year has passed since last update.

Personal Access Tokenをコミットせずに、Github PackagesをPrivateに使う方法

Posted at

前提

私は普段はmacOSでNodeのパッケージ管理にyarn@berryを使ってますのでyarnベースで解説します。

Github Packagesにプライベートで公開する方法は記述しません。公開された後にそれを利用するベストプラクティスの話です。

Organazationやuser名はご自身の環境に読み替えてください。

[方法1] .npmrcもしくは.yarnrc.ymlをコミットの対象外にする

PrivateなGithub Packagesに公開したパッケージを他のプロジェクトからインストールするには、

npmなら.npmrc、yarnをお使いなら.yarnrc.ymlにご自身のPersonal Access Token(=PAT)(権限はread:packagesのみでOK)を記述します。

yarnrc.yml
yarnPath: .yarn/releases/yarn-3.2.1.cjs
nodeLinker: node-modules

npmScopes:
  'suyama-daichi':
    npmAlwaysAuth: true
    npmRegistryServer: 'https://npm.pkg.github.com/'
    npmPublishRegistry: 'https://npm.pkg.github.com/'
    npmAuthToken: ghp_************************************

npmの場合
//npm.pkg.github.com/:_authToken=ghp_************************************
@suyama-daichi:registry=https://npm.pkg.github.com/

これらのファイルを .gitignoreに追加するなどしてコミット対象から除外すれば、自身のトークンがコミットされることはありません。

[方法2]環境変数を参照する

簡単な構成なら方法1でもいいのですが、.npmrcyarnrc.ymlに記述される設定はレジストリの認証情報だけではないので、ファイルごとコミット対象外にするのは得策ではないです。

それでは、PATをVSCodeで実行されるターミナルの環境変数に含めてしまい、それを構成ファイルから参照ましょう。

VSCodeの settings.jsonで設定できます。

settings.json
{
  // 
  "terminal.integrated.env.osx": {
    "GITHUB_PACKAGE_TOKEN": "ghp_************************************"
  }
  // 
}

Windowsの場合
settings.json
{
  // 
  "terminal.integrated.env.linux": {
    "GITHUB_PACKAGE_TOKEN": "ghp_************************************"
  }
  // 
}

プロジェクトごとに設定するならsettings.jsonではなく.code-workspaceを使えます。

.npmrcyarnrc.ymlは環境変数を参照できます。

yarnrc.yml
yarnPath: .yarn/releases/yarn-3.2.4.cjs
nodeLinker: node-modules

npmScopes:
  'suyama-daichi':
    npmAlwaysAuth: true
    npmRegistryServer: 'https://npm.pkg.github.com/'
    npmPublishRegistry: 'https://npm.pkg.github.com/'
    npmAuthToken: ${GITHUB_PACKAGE_TOKEN}

npmの場合
//npm.pkg.github.com/:_authToken=${GITHUB_PACKAGE_TOKEN}
@suyama-daichi:registry=https://npm.pkg.github.com/

setting.jsonの設定を反映させるために、ターミナルを再起動します(VSCodeでもOK)

インストール

これで、プライベートパッケージをインストールできます。

yarn add -D @suyama-daichi/sample-types
npmの場合 ``` npm install -D @suyama-daichi/sample-types ```
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0