乐闻世界logo
搜索文章和话题

How to use pnpm in diferent Gitlab CI stages

4 个月前提问
3 个月前修改
浏览次数83

1个答案

1

When using GitLab CI/CD, pnpm (Performant npm) can be integrated as an efficient package management tool in different stages to optimize the build and deployment process. Here are the steps and examples of using pnpm at different stages in GitLab CI:

1. Preparation stage: Install pnpm

In the GitLab CI configuration file .gitlab-ci.yml, you can set up an initialization stage to install pnpm. As pnpm handles dependencies and caching more efficiently, this can improve the speed of subsequent steps.

yaml
stages: - setup - build - test - deploy install_pnpm: stage: setup image: node:latest script: - npm install -g pnpm cache: key: ${CI_COMMIT_REF_SLUG} paths: - .pnpm-store

In this stage, we used the official Node image and installed pnpm globally. In addition, we configured caching to store pnpm repository, reducing download time in subsequent steps.

2. Build stage: Install dependencies and build using pnpm

In the build stage, we use pnpm to install all necessary dependencies and execute build scripts.

yaml
build_app: stage: build image: node:latest script: - pnpm install --frozen-lockfile - pnpm run build cache: key: ${CI_COMMIT_REF_SLUG} paths: - .pnpm-store - node_modules/ artifacts: paths: - build/ expire_in: 1 hour

Here, pnpm install --frozen-lockfile ensures that dependencies are installed precisely using lock files, while pnpm run build executes the build process. We also cache the node_modules directory to speed up subsequent steps and set the build artifacts as artifacts to be saved.

3. Test stage: Run tests using pnpm

In the test stage, we use pnpm to execute test scripts.

yaml
test_app: stage: test image: node:latest script: - pnpm install - pnpm test cache: key: ${CI_COMMIT_REF_SLUG} paths: - .pnpm-store - node_modules/ artifacts: when: always reports: junit: test-results.xml

Here, in addition to installing dependencies and running tests, we also generate test reports. Using the reports option of artifacts, test results can be exported in JUnit format, which is used for visualizing test reports in GitLab CI.

4. Deployment stage: Deploy using pnpm

Finally, in the deployment stage, pnpm can be used to execute deployment scripts.

yaml
deploy_app: stage: deploy image: node:latest script: - pnpm install --production - pnpm run deploy cache: paths: - .pnpm-store - node_modules/

During deployment, only production dependencies are installed using pnpm install --production, which reduces the size of the deployment package and improves deployment efficiency. Then use pnpm run deploy to execute the deployment process.

By using pnpm in different stages of GitLab CI in a reasonable way, the efficiency and performance of the CI/CD process can be significantly improved.

2024年6月29日 12:07 回复

你的答案