Husky 准备脚本未能部署 Firebase 功能

Atu*_*pta 6 npm firebase google-cloud-functions husky firebase-cli

我已经husky在我的 npm 项目中安装了prepare如下脚本

{
  "name": "functions",
  "scripts": {
    "build": "tsc",
    "start": "npm run serve",
    "deploy": "firebase deploy --only functions",
    "prepare": "husky install functions/.husky"
  }
  "dependencies": {
    "firebase-admin": "^11.4.1",
    "firebase-functions": "^4.1.1",
  },
  "devDependencies": {
    "husky": "^8.0.2",
    "typescript": "^4.9.4"
  }
}
Run Code Online (Sandbox Code Playgroud)

husky声明为devDependencies这个 npm 模块仅在本地开发时需要,在运行时应用程序中不需要。

所以当我运行时npm run deploy,我收到以下错误

i  functions: updating Node.js 16 function funName(us-central1)...
Build failed:

> prepare
> husky install functions/.husky

sh: 1: husky: not found
npm ERR! code 127
npm ERR! path /workspace
npm ERR! command failed
npm ERR! command sh -c -- husky install functions/.husky
Run Code Online (Sandbox Code Playgroud)

这个错误明确表明husky没有安装。

一种可能的解决方案是创建一个prepare.js脚本,检查脚本是否在本地开发或 Firebase 服务器中运行(以准备项目),然后有条件地运行huskynpm 模块命令

Sam*_*rhe 10

我刚刚遇到了这个完全相同的问题,但是使用tsc. 我不确定为什么,但prepare部署时脚本也在云功能中运行(不仅仅是本地)。但是,考虑到您可能在 firebase.json 的列表中包含该node_modules目录functions.ignore,node_modules 目录不会作为部署的一部分上传,因此husky当脚本在云函数环境中运行时,该包对脚本不可见。

无论哪种方式,您可能都不需要在函数环境中运行 husky 脚本,因此您可以添加一个条件来检查通常在函数环境中设置的环境变量(在我的情况下使用环境变量GOOGLE_FUNCTION_TARGET) ,并且仅在未设置该环境时运行该命令。由于准备脚本的运行方式,您还需要将其包装在 bash 脚本中,而不是将其内联添加到 package.json 中。

例如,这是我的scripts/prepare.sh文件的内容。

#!/bin/bash
set -o verbose

# Only run if the GOOGLE_FUNCTION_TARGET is not set
if [[ -z "$GOOGLE_FUNCTION_TARGET" ]]; then
    npm run build
fi

Run Code Online (Sandbox Code Playgroud)

然后我在 package.json 准备脚本中使用它:

// ...
"prepare": "./scripts/prepare.sh",
// ...
Run Code Online (Sandbox Code Playgroud)

可能有更好的解决方案,但这就是我让它为我工作的方法。希望这可以帮助!