如何在CircleCI不同作业间共享npm install结果以避免重复执行?
Absolutely! You can cut down on that redundant npm install run by sharing the dependency installation results between your build and deploy jobs in CircleCI. There are two solid approaches to do this—Workspaces and Dependency Caching—let’s walk through both with your config.
Using CircleCI Workspaces
Workspaces let you share files directly between jobs in the same workflow. This is perfect if your deploy job always runs right after build:
version: 2 jobs: build: docker: - image: circleci/node:7.10 steps: - checkout - run: npm install - run: npm run lint # Save the node_modules folder to a shared workspace - persist_to_workspace: root: . paths: - node_modules deploy: machine: true steps: - checkout # Pull the pre-installed node_modules from the workspace - attach_workspace: at: . - run: npm run build
How it works:
- The
persist_to_workspacestep in thebuildjob saves yournode_modulesdirectory to a workspace that’s accessible by subsequent jobs. - The
attach_workspacestep indeploypulls that folder into the job’s environment, so you can skipnpm installentirely and jump straight to your build command.
Using Dependency Caching
Caching stores your node_modules in CircleCI’s persistent storage, which works well if jobs might run independently or you want to reuse dependencies across multiple workflows:
version: 2 jobs: build: docker: - image: circleci/node:7.10 steps: - checkout # Try to restore cached node_modules first - restore_cache: keys: # Use package-lock.json checksum to ensure cache matches dependencies - v1-dependencies-{{ checksum "package-lock.json" }} # Fallback to latest cache if no exact match exists - v1-dependencies- - run: npm install # Save the cache after successful installation - save_cache: paths: - node_modules key: v1-dependencies-{{ checksum "package-lock.json" }} - run: npm run lint deploy: machine: true steps: - checkout # Restore the same cache used by the build job - restore_cache: keys: - v1-dependencies-{{ checksum "package-lock.json" }} - v1-dependencies- - run: npm run build
How it works:
- The
restore_cachestep checks for a cachednode_modulesfolder tied to yourpackage-lock.json(orpackage.json) checksum. If found, it skips the fullnpm install. - If no cache exists (e.g., first run or dependency changes),
npm installruns normally, and thesave_cachestep stores the newnode_modulesfor future jobs.
Which should you choose?
- Workspaces: Best for sequential jobs where
deployalways followsbuild—it’s a fast, direct file transfer. - Caching: Better for independent jobs or reusing dependencies across multiple workflows (like PR builds and main branch deployments).
内容的提问来源于stack exchange,提问作者LiranC
相关产品推荐
相关产品推荐

