编写 Jenkins 管道共享库以发布到 Nexus NPM 存储库

Writing a Jenkins Pipeline Shared Library to publish to Nexus NPM repository

我曾经使用包含发布阶段的 DSL 管道将我的 NPM 项目发布到 Nexus,步骤如下:

stage ('Publish') {
  nodejs(nodeJSInstallationName: 'Node LTS', configId: '123456ab-1234-abcd-1234-f123d45e6789') {
    sh 'npm publish'
  }
}

我在我的 Jenkins 上安装了一个名为 "Node LTS" 的 NodeJS 和一个带有此 configId 的 npmrc 配置文件。

现在我想将这个阶段导出到 groovy SharedLib 中。 根据 Declarative Pipeline documentation and this nodejs-plugin issue,我可以这样写:

    stage('Publish') {
        tools {
            nodejs 'Node LTS'
        }
        steps {
            sh 'npm publish'
        }
    }

但这不会设置当前在我的 npmrc 配置文件中的身份验证配置:

registry=http://my-nexus/repository/npm-private/
_auth="some=base=64=credential=="
always-auth=true

是否知道使用声明性语法检索此配置并防止出现此错误消息?

npm ERR! code ENEEDAUTH
npm ERR! need auth auth required for publishing
npm ERR! need auth You need to authorize this machine using `npm adduser`

查看 npm 日志文件并阅读文档,我最终发现最好的解决方案是在我的 package.json 文件中指定以下发布配置:

{
  "name": "@my-company/my-project",
  ...
  "publishConfig": {
    "registry": "http://my-nexus/repository/npm-private/"
  },
  ...
}

我保留 .npmrc 配置:

registry=http://my-nexus/repository/npm-private/
_auth="some=base=64=credential=="
always-auth=true

注意:在我的例子中,自动化脚本需要always-authhttps://docs.npmjs.com/misc/config

我努力将节点包从 jenkins 管道发布到 nexus 3,这对我有用。它可能会对某人有所帮助。

pipeline {

    agent any

    environment {
        registryCredentials = "nexus"        
        registryPrivate = "http://nexus:8081/repository/your-nexus-repo/" // nexus repository
    }

    stages {

        stage('Publish') {

            steps {
                script {
                    nodejs('your-jenkins-nodejs-name') {
                        sh("rm ~/.npmrc || echo 'trying to remove .npmrc'") // remove .npmrc

                        // this token is copied from ~/.npmrc file after a interactive npm login
                        // do a npm login to your nexus npm hosted private repo and get the token
                        sh 'echo "//nexus:8081/repository/vinsystems-npm/:_authToken=NpmToken.302af6fb-9ad4-38cf-bb71-57133295c7ca" >> ~/.npmrc'

                        sh("cd ./WebClientWorkspace && yarn install")
                        sh("cd ..")

                        sh("yarn publish ./path/to/your/js-library --registry=${registryPrivate} --registry=${registryPrivate} --non-interactive --verbose")
                    }
                }
            }
        }
    }
}