Gerenciar pacotes Node.js

Nesta página, descrevemos as seguintes tarefas:

  • Como visualizar e excluir pacotes e versões de pacote
  • Como visualizar, criar, atualizar e excluir tags

Antes de começar

  1. Se não existir um repositório de destino, crie um novo repositório.
  2. Verifique se você tem as permissões necessárias para o repositório.
  3. Configure a autenticação do npm.
  4. (Opcional) Configure padrões para comandos gcloud.
  5. Se você estiver usando o auxiliar de credenciais do npm para autenticação, receba um token de acesso antes de se conectar para um repositório com NPM.

Funções exigidas

Para receber as permissões necessárias para gerenciar pacotes, peça ao administrador para conceder a você os seguintes papéis do IAM no repositório:

Para mais informações sobre como conceder papéis, consulte Gerenciar acesso.

Também é possível conseguir as permissões necessárias com papéis personalizados ou outros papéis predefinidos.

Como conseguir um token de acesso

Os tokens de acesso são válidos por 60 minutos. Gere um token de acesso em breve antes de executar comandos que interagem com repositórios.

Para receber um token, use uma destas opções:

  • Use o comando npx para atualizar o token de acesso.

    1. Verifique se as credenciais para se conectar ao registro npm público estão no arquivo de configuração do npm do usuário, ~/.npmrc.

    2. Execute o seguinte comando no diretório do projeto Node.js.

      npx google-artifactregistry-auth
      

      Se o repositório do Artifact Registry estiver definido como o registro global e o pacotes sem escopo, use o seguinte comando para que o pode fazer o download do auxiliar de credenciais do registro npm público em vez do repositório do Artifact Registry.

      npm_config_registry=https://registry.npmjs.org npx google-artifactregistry-auth
      
  • Adicione um script ao arquivo package.json no seu projeto.

    "scripts": {
     "artifactregistry-login": "npx google-artifactregistry-auth"
    }
    

    Execute o script no diretório do projeto do Node.js.

    npm run artifactregistry-login
    

O Artifact Registry lê as configurações do repositório do Artifact Registry no arquivo .npmrc do projeto e as usa para adicionar credenciais de token ao seu usuário .npmrc. Armazenar o token no arquivo .npmrc do usuário isola seu credenciais do código-fonte e do sistema de controle de origem.

Como adicionar pacotes

Modos de repositório: padrão

Só é possível publicar uma versão específica de um pacote uma vez. Essa é uma restrição de npm para garantir que o conteúdo de uma versão de pacote publicada seja sempre o mesmo. Como resultado, você não poderá:

  • Substituir uma versão do pacote publicando-a novamente no repositório
  • Remover um pacote ou sua versão do repositório e, em seguida, publicar um pacote com o mesmo nome e número da versão

Se você não especificar uma tag ao publicar um pacote, o npm adicionará a tag latest. Para simplificar a instalação dos pacotes em um estágio específico de desenvolvimento, considere publicar os pacotes com uma tag, como beta ou dev.

O Artifact Registry aplica nomes de pacotes alfanuméricos em letras minúsculas ao npm pacotes.

Para adicionar um pacote:

  1. Confira se o nome do pacote em package.json inclui o escopo configurado para o repositório. O exemplo a seguir mostra um pacote com o escopo dev-repo.

    "name": "@dev-repo/my-package"
    
  2. Se você estiver usando o auxiliar de credenciais para autenticar com um token de acesso, consiga um novo token.

  3. Adicione pacotes ao repositório. Use um comando npm ou yarn.

    Para incluir uma tag no pacote, inclua a flag --tag e substitua TAG. com a tag que você quer usar. Se você não incluir a flag --tag, o npm define automaticamente a tag como latest.

    npm publish --tag=TAG
    
    yarn publish --tag TAG
    

Como visualizar pacotes e versões

Modos de repositório: padrão, remoto, virtual

Para receber informações de pacote com npm ou yarn:

  1. Se você estiver usando o auxiliar de credenciais para autenticar com um token de acesso, consiga um novo token.

  2. Execute o comando apropriado:

    npm view
    
    yarn info
    

To view packages and package versions using the Google Cloud console or gcloud:

Console

  1. Open the Repositories page in the Google Cloud console.

    Abrir a página Repositórios

  2. In the repository list, click the appropriate repository.

    The Packages page lists the packages in the repository.

  3. Click a package to view versions of the package.

gcloud

To list packages in a repository, run the following command:

gcloud artifacts packages list [--repository=REPOSITORY] [--location=LOCATION]

Where

  • REPOSITORY is the name of the repository. If you configured a default repository, you can omit this flag to use the default.
  • LOCATION is a regional or multi-regional location. Use this flag to view repositories in a specific location. If you configured a default location, you can omit this flag to use the default.

To view versions of a package, run the following command:

gcloud artifacts versions list --package=PACKAGE \
    [--repository=REPOSITORY] [--location=LOCATION]

Where

  • PACKAGE is the ID of the package or fully qualified identifier for the package.
  • REPOSITORY is the name of the repository. If you configured a default repository, you can omit this flag to use the default.
  • LOCATION is a regional or multi-regional location. Use this flag to view repositories in a specific location. If you configured a default location, you can omit this flag to use the default.

Visualizar pacotes e versões no console do Google Cloud ou CLI gcloud está disponível apenas para repositórios padrão e remotos.

Para repositórios remotos, a lista retornada deve incluir todos os repositórios dependências transitivas que são armazenadas em cache no repositório.

Como listar arquivos

Modos de repositório: padrão, remoto

É possível listar arquivos em um repositório, arquivos em todas as versões de um ou arquivos em uma versão específica de um pacote.

Para todos os comandos a seguir, você pode definir um número máximo de arquivos a serem retornados adicionando a sinalização --limit ao comando.

Para listar todos os arquivos no projeto, repositório e local quando os valores padrão estiverem configurados:

gcloud artifacts files list

Para listar arquivos em um projeto, repositório e local especificados, execute o comando:

gcloud artifacts files list \
    --project=PROJECT \
    --repository=REPOSITORY \
    --location=LOCATION

Para listar arquivos de todas as versões de um pacote específico:

gcloud artifacts files list \
    --project=PROJECT \
    --repository=REPOSITORY \
    --location=LOCATION \
    --package=PACKAGE

Para listar arquivos de uma versão específica do pacote:

gcloud artifacts files list \
    --project=PROJECT \
    --repository=REPOSITORY \
    --location=LOCATION \
    --package=PACKAGE \
    --version=VERSION
Para listar arquivos de uma tag específica:

gcloud artifacts files list \
    --project=PROJECT \
    --repository=REPOSITORY \
    --location=LOCATION \
    --package=PACKAGE \
    --tag=TAG

Substitua os seguintes valores:

  • LOCATION: o regional ou multirregional local do repositório.
  • PROJECT: seuID de projeto no Google Cloud. Caso o ID do projeto contenha dois pontos (`:`), consulte Projetos com escopo de domínio.
  • REPOSITORY: o nome do repositório em que a imagem são armazenados.
  • PACKAGE: o nome do pacote.
  • VERSION: a versão do pacote.
  • TAG: a tag associada ao pacote.

Exemplos

Considere as seguintes informações de pacote:

  • Projeto: my-project
  • Repositório: my-repo
  • Local do repositório: us-west1
  • Pacote: my-app

O comando a seguir lista todos os arquivos no repositório my-repo na Local us-west1 no projeto padrão:

gcloud artifacts files list \
    --location=us-west1 \
    --repository=my-repo
O comando a seguir lista os arquivos na versão 1.0 do pacote.

gcloud artifacts files list \
    --project=my-project \
    --location=us-west1 \
    --repository=my-repo \
    --package=my-app \
    --version=1.0
O comando a seguir lista os arquivos na versão do pacote com o marcar 1.0-dev

gcloud artifacts files list \
    --project=my-project \
    --location=us-west1 \
    --repository=my-repo \
    --package=my-app \
    --tag=1.0-dev

Como marcar pacotes

Modos de repositório: padrão

You can view, add, update, and delete tags. Tags can help you manage semantic versions of your packages and streamline installation of packages at a specific stage of development.

For example, you can tag the current release candidate build with rc. Your team can then install the correct version based on the tag instead of a version specifier, and unpublishing unused pre-release versions won't break your dependencies on the release candidate package.

Viewing tags

To view tags for a package:

Console

  1. Open the Repositories page in the Google Cloud console.

    Abrir a página Repositórios

  2. Click the package to view versions and the associated tags.

  3. Select the package version to tag.

  4. In the row of the selected version, click More actions (More actions), and then click Edit tags.

  5. Type new tags into the field and then click SAVE.

gcloud

Run the command:

gcloud artifacts tags list --package=PACKAGE \
    [--repository=REPOSITORY] [--location=LOCATION]

Where

  • PACKAGE is the name of the package in the repository.
  • REPOSITORY is the name of the repository. If you configured a default repository, you can omit this flag to use the default.
  • LOCATION is a regional or multi-regional location. Use this flag to view repositories in a specific location. If you configured a default location, you can omit this flag to use the default.

For example, to view tags for the package my-package in the repository my-repo in the default location, run the command:

gcloud artifacts tags list --package=my-pkg --repository=my-repo

Creating tags

You can create a tag for a specific version of a package.

To tag an existing image in a repository:

Console

  1. Open the Repositories page in the Google Cloud console.

    Abrir a página Repositórios

  2. Click the package to view versions of the package.

  3. Select the package version to tag.

  4. In the row of the selected version, click More actions (More actions), and then click Edit tags.

  5. Type new tags into the field and then click SAVE.

gcloud

Run the following command:

gcloud artifacts tags create TAG --package=PACKAGE \
    version=VERSION [--location=LOCATION] [--repository=REPOSITORY]

Where

  • TAG is the tag you want to apply to the package.
  • PACKAGE is the name of the package in the repository.
  • VERSION is version of the package that you want to tag.
  • LOCATION is a regional or multi-regional location. Use this flag to view repositories in a specific location. If you configured a default location, you can omit this flag to use the default.
  • REPOSITORY is the name of the repository. If you configured a default repository, you can omit this flag to use the default.

For example, to create the tag release-candidate for version 1.0.0 of package my-package in the repository my-repo in the default location, run the command:

gcloud artifacts tags create release-candidate --version=1.0.0 \
    --package=my-pkg --repository=my-repo

Updating tags

You can change a tag associated with a package version.

To change an existing tag:

Console

  1. Open the Repositories page in the Google Cloud console.

    Abrir a página Repositórios

  2. Click the package to view versions of the package.

  3. Select the package version with the tag to change.

  4. In the row of the selected version, click More actions (More actions), and then click Edit tags.

  5. Edit the tag and then click SAVE.

gcloud

Run the following command:

gcloud artifacts tags update TAG --package=PACKAGE \
    version=VERSION [--location=LOCATION] [--repository=REPOSITORY]

Where

  • TAG is the tag you want to apply to the package.
  • PACKAGE is the name of the package in the repository.
  • VERSION is version of the package that you want to tag.
  • LOCATION is a regional or multi-regional location. Use this flag to view repositories in a specific location. If you configured a default location, you can omit this flag to use the default.
  • REPOSITORY is the name of the repository. If you configured a default repository, you can omit this flag to use the default.

For example, to change the tag for version 1.0.0 of package my-package to production in the repository my-repo in the default location, run the command:

gcloud artifacts tags update production --version=1.0.0 \
    --package=my-pkg --repository=my-repo

Untagging package versions

You can remove an existing tag from a package version.

To remove a tag:

Console

  1. Open the Repositories page in the Google Cloud console.

    Abrir a página Repositórios

  2. Click the image to view versions of the image.

  3. Select the image version to untag.

  4. In the row of the selected version, click More actions (More actions), and then click Edit tags.

  5. Delete the tag and then click SAVE.

gcloud

Run the following command:

gcloud artifacts tags delete TAG --package=PACKAGE \
    [--location=<LOCATION] [--repository=REPOSITORY]

Where

  • TAG is the tag you want to apply to the package.
  • PACKAGE is the name of the package in the repository.
  • LOCATION is a regional or multi-regional location. Use this flag to view repositories in a specific location. If you configured a default location, you can omit this flag to use the default.
  • REPOSITORY is the name of the repository. If you configured a default repository, you can omit this flag to use the default.

For example, to remove the tag release-candidate from package my-package in the repository my-repo in the default location, run the command:

gcloud artifacts tags delete release-candidate --package=my-pkg \
    --repository=my-repo

Como instalar pacotes

Modos de repositório: padrão, remoto, virtual

Para instalar um pacote a partir do repositório de pacotes do Node.js:

  1. Se você estiver usando o auxiliar de credenciais para autenticar com um token de acesso, consiga um novo token.

  2. Use o comando npm install ou yarn add.

    npm

    Para instalar a versão com a tag latest:

    npm install @SCOPE/PACKAGE
    

    Para instalar a versão com uma tag diferente:

    npm install @SCOPE/PACKAGE@TAG
    

    Para instalar uma versão específica:

    npm install @SCOPE/PACKAGE@VERSION
    

    yarn

    Para instalar a versão com a tag latest:

    yarn add @SCOPE/PACKAGE
    

    Para instalar a versão com uma tag diferente:

    yarn add @SCOPE/PACKAGE@TAG
    

    Para instalar uma versão específica:

    yarn add @SCOPE/PACKAGE@VERSION
    

    Substitua os seguintes valores:

    • SCOPE é o escopo associado ao repositório. Se as O repositório de pacotes Node.js não está configurado com um escopo. Omita @SCOPE/ no comando.
    • PACKAGE é o nome do pacote no repositório.
    • TAG é a tag da versão que você quer instalar.
    • VERSION é o número da versão que você quer instalar.

Ao especificar um pacote como dependência em package.json, verifique se inclua o escopo do repositório. O exemplo a seguir mostra o escopo @dev-repo de um pacote chamado my-package.

"dependencies": {
  "@dev-repo/my-package": ">=1.0.0"
}

Para repositórios padrão, você faz o download de um pacote diretamente do repositório.

Para um repositório remoto, faça o download de uma cópia em cache do pacote e dependências. Se não houver uma cópia em cache, será feito o download do repositório remoto o pacote da origem upstream e o armazena em cache antes de disponibilizá-lo para você. É possível verificar se o repositório remoto recuperou os pacotes do origem upstream visualizando a lista de pacotes no repositório.

Para um repositório virtual, o Artifact Registry pesquisa repositórios upstream para o pacote solicitado.

  • Os repositórios remotos upstream vão fazer o download e armazenar em cache o pacote solicitado se uma cópia em cache não existe. Os repositórios virtuais disponibilizam somente solicitações pacotes, eles não os armazenam.
  • Se você solicitar uma versão disponível em mais de um repositório, o Artifact Registry escolherá um repositório upstream para usar com base nas configurações de prioridade definidas para o repositório virtual.

Por exemplo, considere um repositório virtual com as seguintes configurações de prioridade para repositórios upstream:

  • main-repo: prioridade definida como 100
  • secondary-repo1: prioridade definida como 80.
  • secondary-repo2: prioridade definida como 80.
  • test-repo: prioridade definida como 20.

main-repo tem o valor de prioridade mais alto, então o repositório virtual sempre pesquisa primeiro.

Tanto secondary-repo1 quanto secondary-repo2 têm prioridade definida como 80. Se um O pacote solicitado não está disponível em main-repo, o Artifact Registry pesquisa esses repositórios a seguir. Como ambas têm o mesmo valor de prioridade, O Artifact Registry pode disponibilizar um pacote de qualquer repositório se a versão estiver disponível em ambas.

test-repo tem o menor valor de prioridade e servirá um artefato armazenado se nenhum dos outros repositórios upstream a tem.

Como excluir pacotes

Modos de repositório: padrão, remoto

É possível excluir um pacote e todas as versões dele ou excluir uma versão específica.

  • Depois de excluir um pacote, não é possível desfazer a ação.
  • Para repositórios remotos, apenas a cópia em cache do pacote é excluída. A a origem não é afetada. Se você excluir um pacote armazenado em cache, O Artifact Registry vai fazer o download e armazenar em cache novamente na próxima vez que recebe uma solicitação para a mesma versão do pacote.

Depois que uma versão do pacote é publicada, não é possível republicar um pacote com o mesmo nome e combinação de versões, mesmo após excluir a versão. Esta é uma npm constraints para garantir que o conteúdo de uma versão de pacote publicada seja sempre o mesmo.

Se você quiser incentivar os usuários a instalar uma versão atualizada do pacote, use o comando npm deprecate para marcar a versão antiga do pacote como obsoleta. Quando um usuário tenta instalar o pacote obsoleto, o Artifact Registry retorna um aviso de suspensão de uso.

Before you delete a package or package version, verify that any you have communicated or addressed any important dependencies on it.

To delete a package:

Console

  1. Open the Repositories page in the Google Cloud console.

    Abrir a página Repositórios

  2. In the repository list, click the appropriate repository.

    The Packages page lists the packages in the repository.

  3. Select the package that you want to delete.

  4. Click DELETE.

  5. In the confirmation dialog box, click DELETE.

gcloud

Run the following command:

gcloud artifacts packages delete PACKAGE \
    [--repository=REPOSITORY] [--location=LOCATION] [--async]

Where

  • PACKAGE is the name of the package in the repository.
  • REPOSITORY is the name of the repository. If you configured a default repository, you can omit this flag to use the default.
  • LOCATION is a regional or multi-regional location. Use this flag to view repositories in a specific location. If you configured a default location, you can omit this flag to use the default.
  • --async Return immediately, without waiting for the operation in progress to complete.

To delete versions of a package:

Console

  1. Open the Repositories page in the Google Cloud console.

    Abrir a página Repositórios

  2. In the repository list, click the appropriate repository.

    The Packages page lists the packages in the repository.

  3. Click a package to view versions of that package.

  4. Select versions that you want to delete.

  5. Click DELETE.

  6. In the confirmation dialog box, click DELETE.

gcloud

Run the following command:

gcloud artifacts versions delete VERSION \
    --package=PACKAGE \
    [--repository=REPOSITORY] [--location=LOCATION] \
    [--async]

Where

  • PACKAGE is the name of the package in the repository.
  • REPOSITORY is the name of the repository. If you configured a default repository, you can omit this flag to use the default.
  • LOCATION is a regional or multi-regional location. Use this flag to view repositories in a specific location. If you configured a default location, you can omit this flag to use the default.
  • --async returns immediately, without waiting for the operation in progress to complete.

A seguir