前言
strapi 是一个使用 node 写的 headless CMS,当然这篇文章不是说 strapi 怎么使用,而是说一下怎么安装,简单来说就是让 npx create-strapi-app@latest my-strapi-project --quickstart
这条命令跑起来。可能你会说这不很简单嘛,不就 cv 一下的事。正常来说确实很简单,但是假如你的工作环境不能上魔法,那事情就变得复杂了。这篇文章就说说在局内环境下怎么让这条命令跑起来。
npm
我操作的电脑已经安装了 nvm(node 的版本管理工具),并且安装了 node 的 18.17.1 的版本。因为 strapi v4 要求的是 v18 和 v20,所以这个没有问题,而 node 的 18.17.1 的版本自带 npm 的 9.6.7 版本,要让 npm 可以拉取包,需要先配置国内镜像,一般会使用淘宝提供的镜像。
npm config set registry "https://registry.npmmirror.com/"
然后执行 npx create-strapi-app@latest my-strapi-project --quickstart
sharp
这个过程中会看到 react 等这些包被下载,当很快就在下载 sharp 这个包时被卡主了。具体报错是这样的
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c (node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy)
npm ERR! sharp: Downloading https://github.com/lovell/sharp-libvips/releases/download/v8.14.5/libvips-8.14.5-win32-x64.tar.br
npm ERR! sharp: Please see https://sharp.pixelplumbing.com/install for required dependencies
npm ERR! sharp: Installation error: unable to verify the first certificate
这个问题也是下载源的问题。需要在命令行执行
npm config set sharp_binary_host "https://npmmirror.com/mirrors/sharp"
npm config set sharp_libvips_binary_host "https://npmmirror.com/mirrors/sharp-libvips"
nvm
如果执行以上两条命令,很快就会收获到一条报错
npm ERR! `sharp_binary_host` is not a valid npm option
如果要让这条命令生效,需要把 npm 回退到 v8 版本。npm install -g npm@^8
。因为我不太想降级 npm,毕竟和 node 版本一起绑定的,所以打算使用 nvm 来安装 node 16.20.0 这个版本,这个版本自带的 npm 是 v8 的。于是执行 nvm install 16.20.0
,很快又卡主了,半天看不到控制台有输出。这个问题可能是最近才有的,因为我记得安装 v18 时没有遇到。这个又是源的问题,需要执行
nvm npm_mirror "https://npmmirror.com/mirrors/npm/"
nvm node_mirror "https://npmmirror.com/mirrors/node/"
better_sqlite3
安装完成 node 16.20.0 版本后,使用 v8 版本的 npm 配置好 sharp 相关的源。然后重新回退到 v18 版本进行安装,这个时候终于安装成功了。但是项目启动时,会发现下面的报错
Error: Could not locate the bindings file. Tried:
→ D:\MyProject\node_modules\better-sqlite3\build\better_sqlite3.node
→ D:\MyProject\node_modules\better-sqlite3\build\Debug\better_sqlite3.node
→ D:\MyProject\node_modules\better-.........
如果查看包文件,会发现确实缺这些文件。这个问题也是下载源的问题。需要配置
npm config set better_sqlite3_binary_host "https://registry.npmmirror.com/-/binary/better-sqlite3"
配置完成后,重新安装 npm install better_sqlite3
这些文件就出现了,然后重新运行项目就可以跑起来了。
总结
在安装 strapi v4 时遇到的各种问题都是下载源的问题,在有的文章中提到的源有的已经过期了,这篇文章提到的源是当前可用的,但是也不能保证未来能用,请试着使用。