加速 npm 安装 [英] Speeding up the npm install

查看:54
本文介绍了加速 npm 安装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在构建过程阶段加速 npm 安装.我的 package.json 有很多包含锁定修订的包列表.我还使用命令

I am trying to speed up the npm install during the build process phase. My package.json has the list of packages pretty much with locked revisions in it. I've also configured the cache directory using the command

npm config set cache /var/tmp/npm-cache --global

然而,在尝试使用 npm install -g --cache 进行安装时,我发现这一步并没有像我期望的那样通过从缓存加载包来减少安装时间.事实上,我怀疑它是否首先使用本地缓存来查找包.

However, on trying to install using npm install -g --cache, I find that this step isn't reducing the time to install by just loading the packages from cache as I would expect. In fact, I doubt if it's even using the local cache to look up packages first.

推荐答案

提出两个更现代的方法:

Proposing two more modern approches:

1) npm ci

使用 npm ci,可从 npm 版本 5.7.0 获得(尽管我推荐 5.7.1 及更高版本,因为 5.7.1a href="https://github.com/npm/npm/issues/19883" rel="noreferrer">破解版) - 这需要 package-lock.json存在,它跳过从 package.json 文件构建依赖树,尊重锁定文件中已解析的依赖 URL.

Use npm ci, which is available from npm version 5.7.0 (although I recommend 5.7.1 and upwards because of the broken release) - this requires package-lock.json to be present and it skips building your dependency tree off of your package.json file, respecting the already resolved dependency URLs in your lock file.

一个非常快提升您的 CI/CD 环境(我们的构建时间减少到原来的四分之一!)和/或确保您的所有开发人员在开发过程中使用相同版本的依赖项(无需在您的 package.json 文件).

A very quick boost for your CI/CD envs (our build time was cut down to a quarter of the original!) and/or to make sure all your developers sit on the same versions of dependencies during development (without having to hard-code strict versions in your package.json file).

但是请注意,npm ci 在安装之前删除了 node_modules/ 目录,因此它不会从任何缓存策略中受益.

Note however that npm ci removes the node_modules/ directory before installing, so it won't benefit from any caching strategies.

2) npm i --prefer-offline

在常规 npm install/npm i 中使用 --prefer-offline 标志.使用这种方法,您需要确保在构建之间(在 CI/CD 环境中)缓存了 node_modules/ 目录.如果在本地找不到特定版本的包,它会安全地回退到网络.

Use the --prefer-offline flag with your regular npm install / npm i. With this approach, you need to make sure you've cached your node_modules/ directory between builds (in a CI/CD environment). If it fails to find packages locally with the specific version, it falls back to the network safely.

这篇关于加速 npm 安装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆