在Ubuntu上使用Node.js进行持续集成可按以下步骤操作:
使用NodeSource仓库安装(推荐)
sudo apt update
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - # 替换为所需版本
sudo apt install -y nodejs
node -v # 验证安装
使用NVM管理多版本(可选)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts # 安装最新LTS版本
nvm use 20 # 切换版本
初始化项目
mkdir my-node-ci && cd my-node-ci
npm init -y
安装开发依赖
npm install --save-dev jest eslint # 示例:测试和代码检查工具
.github/workflows/ci.yml:name: Node.js CI
on: [push, pull_request]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '20'
cache: 'npm'
- run: npm install
- run: npm test # 运行单元测试
- run: npm run lint # 代码检查
.gitlab-ci.yml:stages:
- test
- build
test_job:
stage: test
script:
- npm install
- npm test
Jenkinsfile定义构建步骤,例如:pipeline {
agent any
stages {
stage('Install') {
steps {
sh 'npm install'
}
}
stage('Test') {
steps {
sh 'npm test'
}
}
}
}
npm run lint和npm test确保代码质量。以上步骤可根据项目需求选择工具链,GitHub Actions适合轻量级项目,GitLab CI/CD适合复杂流水线,Jenkins适合企业级定制化场景。