Jenkins前端项目持续部署

前后端分离模式下,手动部署低效,需升级为工程化持续部署。本文介绍在Github新建repo,用vue-cli初始化前端项目,结合Jenkins做前端CD的过程,包括新建、初始化、安装Jenkins及CD配置等,还汇总了常见问题及解决办法,总结为jenkins构建、ssh更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前后端分离的开发模式下,往往前端只需将一个包含js,html,css以及其他静态资源的dist目录发给后端。

最直观的就是vue-cli,create-react-app,自定义脚手架中的npm run build命令,本质上,是webpack,gulp等打包工具去做了编译打包等等工作,最终会生成一个dist目录,它是我们唯一需要提供给后端的内容,

如果代码无bug且只发一次版本(有这么皮的项目吗?),上面这样的方式完全ok。但是如果需要频繁更新版本,那么就需要频繁 打包 发包 接包 部署,这对于前后端来说,都是一个很低效的事情。

因此我们需要将低效的手动式部署,升级为更加先进的工程化的持续部署。

Jenkins就很好的可以做这样的事情,而且公司项目正在正常使用。

下面我将在Github新建一个repo,并且使用vue-cli初始化一个前端项目,最后结合Jenkins做一次前端CD。

local:vue项目 Jenkins服务器
remote:github repo

新建repo

项目地址:https://github.com/FrankKai/f...

初始化项目

vue create demo

下载并安装Jenkins[](https://jenkins.io/doc/pipeli...

  1. Download Jenkins.
  2. Open up a terminal in the download directory.
  3. Run java -jar jenkins.war --httpPort=8080.
  4. Browse to http://localhost:8080.
  5. Follow the instructions to complete the installation.

CD配置

项目(Job)名称:foo-production

源码管理
Git

  • Repositories

    • Repository URL https://github.com/FrankKai/frontend-jenkins-cd.git
    • Credentials frank/*******
  • Branches to build

    • Branch Specifier */master
  • Additional Behaviours

    • Fetch tags
    • Shallow clone
    • Shallow clone depth 0

构建触发器

触发远程构建 (例如,使用脚本)

  • 身份验证令牌

构建环境
Delete workspace before build starts
Abort the build if it’s stuck

  • Time-out strategy Absolute
  • Timeout minutes 5
  • Provide Node & nom bin/folder to PATH

    • NodeJS installation node_8.11.3
    • Npmrc file taboo registry

构建
Execute shell

  • Command

echo $PATH
node —version
npm install -g yarn —registry=https://registry.npm.taobao.org
yarn —version

yarn install

yarn lint
yarn build

Send files or execute commands over SSH
SSH Publishers

  • SSH Server

    • Name nginx-crm
    • Transfers

      • Transfer Set

        • Source files dist/**/*
        • Remove prefix dist

构建后操作
Notify Failure
Notify Success

问题汇总:

  • /Users/Shared/Jenkins下没有Home目录

Jenkins只能运行在Java 8上

  • 管理员密码获取不到

/Users/Shared/Jenkins/Home/secrets/initialAdminPassword
由于secrets目录权限为drwx------,因此需要使用sudo -i切换到文件拥有者root用户。

  • 凭据添加

添加全部的Jenkins凭证即可。

  • Fetch tags

不选择这个在克隆时不会带着tags,在你想访问refspec指定的内容时可以节省时间和空间。

  • Shallow clone

浅克隆,这样git才能不下载项目的历史,如果你只想获得最新版,这样可以节省你的时间和磁盘空间。

  • Shallow clone depth 0

设置一个shallow的深度,这样git才能下载项目最近的历史,节省时间空间。
注:与npm list --depth 0 -g是一个道理。

  • 触发远程构建(例如,使用脚本)

身份验证令牌
JENKINS_URL/job/weidian-crm-preproduction/build?token=TOKEN_NAME 或者 /buildWithParameters?token=TOKEN_NAME
Optionally append &cause=Cause+Text

  • 卡住停止策略

Absolute Deadline Elastic Likely stuck No Activity

  • 如何安装NodeJS Jenkins插件?

系统管理->插件管理
插件安装完成后,就会出现Provide Node & npm bin/ folder to PATH选项。

  • NodeJS Installation无选项

在全局配置的NodeJS中新增NodeJS即可。

  • 没有npmrc文件

需要安装Pipeline NPM Plugin,在系统管理里找到Managed files,再Add a new Config即可。

  • 没有SSH Publishers

安装插件# Publish Over SSH Plugin,远程执行远程linux服务器上的命令。

  • SSH Publisher没有选项

在全局的系统设置中,新增一台ssh服务器。

Started by user 高凯
Building in workspace /Users/Shared/Jenkins/Home/workspace/crm-production
[WS-CLEANUP] Deleting project workspace...
[WS-CLEANUP] Done
Cloning the remote Git repository
Using shallow clone
Cloning repository https://github.com/FrankKai/frontend-jenkins-cd.git
 > git init /Users/Shared/Jenkins/Home/workspace/crm-production # timeout=10
Fetching upstream changes from https://github.com/FrankKai/frontend-jenkins-cd.git
 > git --version # timeout=10
using GIT_ASKPASS to set credentials 
 > git fetch --tags --progress https://github.com/FrankKai/frontend-jenkins-cd.git +refs/heads/*:refs/remotes/origin/* --depth=1
 > git config remote.origin.url https://github.com/FrankKai/frontend-jenkins-cd.git # timeout=10
 > git config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/* # timeout=10
 > git config remote.origin.url https://github.com/FrankKai/frontend-jenkins-cd.git # timeout=10
Fetching upstream changes from https://github.com/FrankKai/frontend-jenkins-cd.git
using GIT_ASKPASS to set credentials 
 > git fetch --tags --progress https://github.com/FrankKai/frontend-jenkins-cd.git +refs/heads/*:refs/remotes/origin/* --depth=1
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision af6a29ef8221d59a533fd6139fd2cb23e7a0e9bd (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f af6a29ef8221d59a533fd6139fd2cb23e7a0e9bd
Commit message: "change"
 > git rev-list --no-walk af6a29ef8221d59a533fd6139fd2cb23e7a0e9bd # timeout=10
Adding all registry entries
copy managed file [taobao registry] to file:/Users/Shared/Jenkins/Home/workspace/crm-production@tmp/config7039915536655380363tmp
[crm-production] $ /bin/sh -xe /Users/Shared/Jenkins/tmp/jenkins2849389808941702160.sh
+ echo /Users/Shared/Jenkins/Home/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node8.11.3/bin:/usr/bin:/bin:/usr/sbin:/sbin
/Users/Shared/Jenkins/Home/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node8.11.3/bin:/usr/bin:/bin:/usr/sbin:/sbin
+ node --version
v8.11.3
+ npm install -g yarn --registry=https://registry.npm.taobao.org
/Users/Shared/Jenkins/Home/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node8.11.3/bin/yarn -> /Users/Shared/Jenkins/Home/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node8.11.3/lib/node_modules/yarn/bin/yarn.js
/Users/Shared/Jenkins/Home/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node8.11.3/bin/yarnpkg -> /Users/Shared/Jenkins/Home/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node8.11.3/lib/node_modules/yarn/bin/yarn.js
+ yarn@1.9.4
updated 1 package in 0.643s
+ yarn --version
1.9.4
[crm-production] $ /bin/sh -xe /Users/Shared/Jenkins/tmp/jenkins5038056372914853910.sh
+ yarn install
yarn install v1.9.4
info No lockfile found.
[1/4] Resolving packages...
warning @vue/cli-service > webpack-bundle-analyzer > bfj-node4@5.3.1: Switch to the `bfj` package for fixes and new features!
[2/4] Fetching packages...
[3/4] Linking dependencies...
warning "@vue/cli-plugin-babel > babel-loader@8.0.0" has incorrect peer dependency "@babel/core@^7.0.0".
warning "@vue/cli-plugin-babel > babel-loader@8.0.0" has unmet peer dependency "webpack@>=2".
warning "@vue/cli-plugin-eslint > eslint-loader@2.1.0" has unmet peer dependency "webpack@>=2.0.0 <5.0.0".
[4/4] Building fresh packages...
success Saved lockfile.
Done in 9.80s.
[crm-production] $ /bin/sh -xe /Users/Shared/Jenkins/tmp/jenkins3713308693086114075.sh
+ yarn lint
yarn run v1.9.4
$ vue-cli-service lint
 DONE  No lint errors found!
Done in 1.00s.
+ yarn build
yarn run v1.9.4
$ vue-cli-service build

 DONE  Compiled successfully in 4555ms13:48:31

  File                                 Size               Gzipped

  dist/js/chunk-vendors.df5f2e07.js    78.56 kb           28.33 kb
  dist/js/app.4aef55d1.js              4.31 kb            1.60 kb
  dist/css/app.d63511e4.css            0.33 kb            0.23 kb

  Images and other types of assets omitted.

 DONE  Build complete. The dist directory is ready to be deployed.
 INFO  Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html
      
Done in 7.46s.
SSH: Connecting from host [frankdeiMac.local]
SSH: Connecting with configuration [crm-test] ...
SSH: Disconnecting configuration [crm-test] ...
SSH: Transferred 7 file(s)
Build step 'Send files or execute commands over SSH' changed build result to SUCCESS
Finished: SUCCESS

从日志中我们其实可以发现,Jenkins主要做了2件事:

  • 编译文件*

    • 从git仓库拉取文件到Jenkins
    • Jenkins更新node_modules
    • Jenkins build前端三板斧(html,css,js),一般为npm run build/ yarn build,生成dist目录
  • 发送文件

    • 与后端服务器建立ssh连接
    • 发送dist目录,更新旧目录
    • 断开连接

用一句话总结,其实就是jenkins构建,ssh更新

茅塞顿开的感觉真好!

关于前端自动化构建,还有以下博文可以参考:

参考资料:
https://segmentfault.com/a/1190000010200161
https://juejin.im/post/5ad1980e6fb9a028c42ea1be
https://yezihaohao.github.io/2017/09/09/Jenkins%E5%AE%9E%E7%8E%B0%E5%89%8D%E7%AB%AF%E9%A1%B9%E7%9B%AE%E8%87%AA%E5%8A%A8%E5%8C%96%E9%9B%86%E6%88%90%E6%89%93%E5%8C%85%E9%83%A8%E7%BD%B2/

### Jenkins 实现前端项目持续集成与部署 (CI/CD) #### 1. 安装必要的工具和插件 为了支持前端项目的构建和部署,需确保 Jenkins 已安装以下必要组件: - **Node.js 插件**:用于管理 Node.js 版本及其依赖项。 - **Git Plugin** 或其他版本控制系统的插件,以便拉取源码。 - **Docker Pipeline 插件**(如果计划使用 Docker 部署)。 可以通过 Jenkins 的插件管理中心手动安装这些插件[^1]。 --- #### 2. 创建 Jenkins 构建任务 在 Jenkins Web 页面上新建一个自由风格的任务或流水线任务。以下是两种方式的具体说明: ##### 自由风格任务配置 - **Source Code Management**: 使用 Git 插件指定仓库地址以及分支名称。 - **Build Triggers**: 可选触发器如定时构建 (`Poll SCM`) 或者通过 webhook 接收推送事件自动触发构建。 - **Build Environment**: 如果需要清理工作区,则勾选 `Delete workspace before build starts`。 - **Build Steps**: 添加 Shell 脚本来执行 npm/yarn 命令来安装依赖并打包应用。例如: ```bash #!/bin/bash # 初始化环境变量 export NODE_ENV=production # 清理旧文件 rm -rf node_modules dist package-lock.json || true # 安装依赖包 npm install --silent # 执行构建过程 npm run build ``` ##### 流水线任务定义 对于更复杂的流程推荐采用声明式管道语法描述整个生命周期活动如下所示: ```groovy pipeline { agent any environment { NPM_CONFIG_PRODUCTION = 'true' } stages { stage('Checkout') { steps { git branch: 'main', url: '<your-repo-url>' } } stage('Install Dependencies') { steps { sh ''' echo "Installing dependencies..." npm ci --quiet ''' } } stage('Test') { steps { sh ''' echo "Running tests..." npm test --if-present ''' } } stage('Build Application') { steps { sh ''' echo "Building application..." npm run build ''' } } stage('Deploy to Staging Server via SSH') { when { expression { env.BRANCH_NAME ==~ /release-.*/ } // Only deploy release branches. } steps { sshPublisher( publishers: [ sshPublisherDesc( configName: 'staging-server', transfers: [sshTransfer(cleanRemote: false, sourceFiles: "**/*.zip")], usePromotionTimestamp: false, verbose: true ) ] ) } } /* Optional Stage */ stage('Push Image To Registry And Deploy On Kubernetes Cluster Using Helm Chart'){ when{ allOf{branch 'master';environment name:'ENVIRONMENT',value:'prod'} } steps{ withCredentials([usernamePassword(credentialsId:"dockerhub",passwordVariable:"PASSWD",usernameVariable:"USERNM")] ){ script{ def imageName="myfrontendapp:${env.GIT_COMMIT}" dir("/path/to/dockerfile"){ sh """ docker login -u \$USERNM -p \$PASSWD; docker build . -t ${imageName}; docker push ${imageName} """ helm upgrade my-release ./charts/mychart \ --set image.repository=${imageName} \ --reuse-values } } } } } } } ``` 上述脚本涵盖了从检出代码、测试验证直到最终发布的一系列动作,并且可以根据实际需求调整各个阶段逻辑[^2]。 --- #### 3. 设置目标服务器准备接收部署成果 假如打算直接把静态资源上传至远程主机的话,那么应该提前做好SSH密钥认证授权;要是利用容器化技术分发服务实例则要预先搭建好对应的运行时框架结构比如说Kubernetes集群之类的基础设施建设完毕之后再继续往下走下一步骤操作即可完成全部准备工作啦! --- ### 注意事项 - 确认所有敏感数据都已妥善存储于 Jenkins 凭证管理系统之中而不是硬编码进脚本里头去暴露风险哦! - 对不同类型的前端框架可能还需要额外考虑一些特定参数设定情况下的兼容性问题处理办法才行呢😊
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值