跳到主要内容

pnpm fetch

将 lockfile 中列出包下载到虚拟存储中,包清单被忽略。

使用场景

此命令专门用于加速构建 docker 镜像。

You may have read the official guide to writing a Dockerfile for a Node.js app, if you haven't read it yet, you may want to read it first.

从该指南中,我们学会了如何为使用 pnpm 的项目编写优化的 Dockerfile ,这将类似于

FROM node:20

WORKDIR /path/to/somewhere

RUN corepack enable pnpm && corepack install -g pnpm@latest-9

# Files required by pnpm install
COPY .npmrc package.json pnpm-lock.yaml .pnpmfile.cjs ./

# If you patched any package, include patches before install too
COPY patches patches

RUN pnpm install --frozen-lockfile --prod

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "node", "server.js" ]

只要不更改 .npmrcpackage.jsonpnpm-lock.yaml.pnpmfile.cjs, Docker 构建缓存一直有效至 RUN pnpm install --frozen-lockfile --prod,这在构建 Docker 映像时花费了大部分时间。

但是,对 package.json 的修改可能比我们预期的 频繁得多,因为它不仅包含依赖关系,而且还可能 包含版本号,脚本和其他工具的任意配置。

维护构建 monorepo 项目的 Dockerfile 也很困难,它可能 看起来像

FROM node:20

WORKDIR /path/to/somewhere

RUN corepack enable pnpm && corepack install -g pnpm@latest-9

# Files required by pnpm install
COPY .npmrc package.json pnpm-lock.yaml .pnpmfile.cjs ./

# If you patched any package, include patches before install too
COPY patches patches

# for each sub-package, we have to add one extra step to copy its manifest
# to the right place, as docker have no way to filter out only package.json with
# single instruction
COPY packages/foo/package.json packages/foo/
COPY packages/bar/package.json packages/bar/

RUN pnpm install --frozen-lockfile --prod

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "node", "server.js" ]

如您所见,当您添加或删除子包时,必须更新 Dockerfile。

pnpm fetch 将通过提供仅从 lockfile 中下载包至虚拟存储中来完美地解决上述问题。

FROM node:20

WORKDIR /path/to/somewhere

RUN corepack enable pnpm && corepack install -g pnpm@latest-9

# pnpm fetch does require only lockfile
COPY pnpm-lock.yaml ./

# If you patched any package, include patches before running pnpm fetch
COPY patches patches

RUN pnpm fetch --prod


ADD . ./
RUN pnpm install -r --offline --prod


EXPOSE 8080
CMD [ "node", "server.js" ]

它既适用于简单项目,也适用于 monorepo 项目, --offline 会强制 pnpm 不与package registry通信,因为所有需要的包都应该已经存在于虚拟存储中。

只要 lockfile 没有改变,构建缓存一直有效到 RUN pnpm install -r --offline --prod 这一层,这将为您节省很多时间。

配置项

--dev, -D

只会获取开发包

--prod, -P

不会获取开发包