Jenkins Pipeline 編譯前端 NodeJS 代碼


軟件:
Jenkins 容器:jenkins/jenkins:lts
Jenkins 插件:Git Parameter, Pipeline, NodeJS Plugin

安裝 Jenkins 的步驟就不寫了,我這里使用的是 docker 方式,大家也可以參考我前面的文章:https://www.cnblogs.com/klvchen/p/10593501.html

配置 NodeJS

"Manage Jenkins" -> "Global Tool Configuration" -> 輸入名字:"NodeJS 14.11.0",自動安裝

配置 git 拉取代碼的憑證和 ssh 登錄憑證

"Manage Jenkins" -> "Manage Credentials"

注意,下面兩個 ID 后面會用到
git 拉取代碼的ID: 1639462c-7254-497a-b352-0fba485a0fcb
ssh 登錄憑證的ID:cb9d8a50-0141-4316-97df-8da33e5a3ab0

配置 npm 的源為國內淘寶的

"Manage Jenkins" -> "Managed files" -> "Add a new Config" -> 選擇 "Npm config file" -> 提交
在 "Content" 處添加

registry =  https://registry.npm.taobao.org


注意這里的 ID:92a915c5-1e3b-4003-9334-5dd9e6127bb8,在 Build 階段會指定該 ID

創建 Pipeline 項目 klvchen_vue

在 "Pipeline Script" 中輸入

pipeline {
    agent any
    
    parameters {
        // 選擇分支發布
        gitParameter branchFilter: 'origin/(.*)', defaultValue: 'master', name: 'BRANCH', type: 'PT_BRANCH', listSize: '25'
    }

    stages {
        stage('Git pull') {
            steps {
                // 下載代碼
                git credentialsId: '1639462c-7254-497a-b352-0fba485a0fcb', branch: "${params.BRANCH}", url: 'http://git.klvchen.com/klvchen/klvchen_vue.git'
            }
        }
        
        stage('Build') {
            steps {
                nodejs(nodeJSInstallationName: 'NodeJS 14.11.0', configId: '92a915c5-1e3b-4003-9334-5dd9e6127bb8') {
                    // npm 編譯安裝
                    sh 'npm install && npm run build'
                }
            }
        }
        
        stage('Deploy') {
            steps {                                 
                // 把編譯好的 dist 傳輸到 192.168.0.2 服務器上              
                withCredentials([sshUserPrivateKey(credentialsId: 'cb9d8a50-0141-4316-97df-8da33e5a3ab0', keyFileVariable: 'pem')]) {
                    sh '''
                       scp -i ${pem} -o "StrictHostKeyChecking=no" -r dist root@192.168.0.2:/data/klvchen_project/
                    '''
                }
            }
        }
    }
   
}

npm 換成 yarn 命令

因為 npm 命令安裝第三方包不穩定,可以使用 yarn 來管理

在構建的時候,把 npm 命令換成 yarn

sh '''
    yarn config set registry https://registry.npm.taobao.org/
    yarn install && yarn build
'''


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM