Jenkins入门教程(十一):使用Jenkins构建前端项目

本文将详细介绍如何使用Jenkins构建基于Node.js的前端项目,包括React、Vue等框架的完整构建流程和示例。

配置Node.js环境

安装NodeJS插件后,在全局工具配置中添加Node.js:

  • 进入系统管理 > 全局工具配置
  • 找到NodeJS部分,点击新增NodeJS
  • 名称:Node18
  • 版本:选择18.x LTS版本
  • 可选:配置全局npm包(如yarn、pnpm)

完整前端构建Pipeline

pipeline {
    agent any
    
    tools {
        nodejs 'Node18'
    }
    
    environment {
        CI = 'true'
        NODE_OPTIONS = '--max_old_space_size=4096'
    }
    
    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', url: 'https://github.com/example/react-app.git'
            }
        }
        
        stage('Check Environment') {
            steps {
                sh '''
                    echo "=== Node.js Version ==="
                    node -v
                    
                    echo ""
                    echo "=== NPM Version ==="
                    npm -v
                    
                    echo ""
                    echo "=== Project Info ==="
                    cat package.json | head -20
                '''
            }
        }
        
        stage('Install Dependencies') {
            steps {
                sh '''
                    echo "Installing dependencies..."
                    npm ci
                    
                    echo ""
                    echo "=== Installed Packages ==="
                    npm list --depth=0
                '''
            }
        }
        
        stage('Lint') {
            steps {
                sh '''
                    echo "Running ESLint..."
                    npm run lint || true
                '''
            }
        }
        
        stage('Test') {
            steps {
                sh '''
                    echo "Running tests..."
                    npm test -- --coverage --watchAll=false
                '''
            }
            post {
                always {
                    junit testResults: 'junit.xml', allowEmptyResults: true
                    publishHTML(target: [
                        allowMissing: true,
                        alwaysLinkToLastBuild: true,
                        keepAll: true,
                        reportDir: 'coverage/lcov-report',
                        reportFiles: 'index.html',
                        reportName: 'Coverage Report'
                    ])
                }
            }
        }
        
        stage('Build') {
            steps {
                sh '''
                    echo "Building production bundle..."
                    npm run build
                    
                    echo ""
                    echo "=== Build Output ==="
                    ls -lh build/ || ls -lh dist/
                    
                    echo ""
                    echo "=== Bundle Size ==="
                    du -sh build/ || du -sh dist/
                '''
            }
        }
        
        stage('Archive') {
            steps {
                sh 'tar -czvf frontend-build.tar.gz build/ || tar -czvf frontend-build.tar.gz dist/'
                archiveArtifacts artifacts: 'frontend-build.tar.gz', fingerprint: true
            }
        }
    }
    
    post {
        always {
            cleanWs()
        }
        success {
            echo 'Frontend build completed successfully!'
        }
        failure {
            echo 'Frontend build failed!'
        }
    }
}

执行结果示例

[Pipeline] stage
[Pipeline] { (Check Environment)
[Pipeline] sh
+ echo '=== Node.js Version ==='
=== Node.js Version ===
+ node -v
v18.19.0

+ echo '=== NPM Version ==='
=== NPM Version ===
+ npm -v
10.2.3

[Pipeline] stage
[Pipeline] { (Install Dependencies)
[Pipeline] sh
+ echo 'Installing dependencies...'
Installing dependencies...
+ npm ci
added 1423 packages in 45s

+ echo '=== Installed Packages ==='
=== Installed Packages ===
+ npm list --depth=0
my-react-app@0.1.0 /var/lib/jenkins/workspace/frontend-demo
├── @testing-library/react@14.0.0
├── react@18.2.0
├── react-dom@18.2.0
├── react-scripts@5.0.1
└── typescript@5.0.0

[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] sh
+ echo 'Building production bundle...'
Building production bundle...
+ npm run build

> my-react-app@0.1.0 build
> react-scripts build

Creating an optimized production build...
Compiled successfully.

File sizes after gzip:

  52.35 kB  build/static/js/main.abc123.js
  1.78 kB   build/static/css/main.def456.css

+ echo '=== Build Output ==='
=== Build Output ===
+ ls -lh build/
total 28K
-rw-r--r-- 1 jenkins jenkins 3.2K Feb  8 12:45 asset-manifest.json
-rw-r--r-- 1 jenkins jenkins  534 Feb  8 12:45 index.html
drwxr-xr-x 4 jenkins jenkins 4.0K Feb  8 12:45 static

+ echo '=== Bundle Size ==='
=== Bundle Size ===
+ du -sh build/
256K    build/

使用Docker构建

使用Docker容器提供一致的Node.js环境:

pipeline {
    agent {
        docker {
            image 'node:18-alpine'
            args '-v /var/cache/npm:/root/.npm'  // 缓存npm
        }
    }
    
    stages {
        stage('Build') {
            steps {
                sh '''
                    npm ci
                    npm run build
                '''
            }
        }
    }
}

Vue项目构建示例

pipeline {
    agent {
        docker { image 'node:18-alpine' }
    }
    
    environment {
        VUE_APP_API_URL = 'https://api.example.com'
    }
    
    stages {
        stage('Install') {
            steps {
                sh 'npm ci'
            }
        }
        
        stage('Lint') {
            steps {
                sh 'npm run lint'
            }
        }
        
        stage('Unit Test') {
            steps {
                sh 'npm run test:unit -- --coverage'
            }
        }
        
        stage('Build') {
            steps {
                sh 'npm run build'
                sh 'ls -la dist/'
            }
        }
    }
}

使用pnpm或yarn

pipeline {
    agent {
        docker { image 'node:18-alpine' }
    }
    
    stages {
        stage('Setup pnpm') {
            steps {
                sh '''
                    npm install -g pnpm
                    pnpm -v
                '''
            }
        }
        
        stage('Install') {
            steps {
                sh 'pnpm install --frozen-lockfile'
            }
        }
        
        stage('Build') {
            steps {
                sh 'pnpm build'
            }
        }
    }
}

部署到Nginx

pipeline {
    agent any
    
    stages {
        stage('Build') {
            agent {
                docker { image 'node:18-alpine' }
            }
            steps {
                sh 'npm ci && npm run build'
                stash includes: 'dist/**', name: 'build-output'
            }
        }
        
        stage('Deploy to Nginx') {
            steps {
                unstash 'build-output'
                
                sshagent(['deploy-server-ssh']) {
                    sh '''
                        rsync -avz --delete dist/ user@webserver:/var/www/html/
                        ssh user@webserver 'sudo systemctl reload nginx'
                    '''
                }
            }
        }
    }
}

构建Docker镜像

# Dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
// Jenkinsfile
pipeline {
    agent any
    
    stages {
        stage('Build Image') {
            steps {
                script {
                    def image = docker.build('myapp-frontend:${BUILD_NUMBER}')
                    docker.withRegistry('https://registry.example.com', 'registry-creds') {
                        image.push()
                        image.push('latest')
                    }
                }
            }
        }
    }
}

缓存优化

node_modules目录很大,使用缓存加速构建:

pipeline {
    agent any
    
    stages {
        stage('Install with Cache') {
            steps {
                // 使用npm ci代替npm install
                // npm ci从package-lock.json安装,更快更一致
                sh '''
                    npm cache verify
                    npm ci --prefer-offline
                '''
            }
        }
    }
}

总结

本文详细介绍了使用Jenkins构建前端项目的完整流程,包括React/Vue项目构建、Docker化、部署到Nginx等内容。

下一篇我们将学习Jenkins的分布式构建与Agent节点。

发表回复

后才能评论