[英]Husky prepare script failing firebase function deployment
我在我的 npm 项目中安装了husky
作为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"
}
}
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
这个错误很明显是没有安装husky
。
一种可能的解决方案是创建一个prepare.js
脚本,该脚本检查脚本是否在本地开发或 firebase 服务器(准备项目)中运行,然后有条件地运行husky
npm 模块命令
我刚刚遇到了这个完全相同的问题,但遇到了tsc
。 我不确定为什么,但是prepare
脚本也在部署时在云 function(不仅仅是本地)中运行。 但是,考虑到您可能在 firebase.json 的functions.ignore
列表中有node_modules
目录, husky
目录不会作为部署的一部分上传,因此当脚本在云 function 环境。
您可能不需要 husky 脚本以任何方式在 function 环境中运行,因此您可以添加一个条件来检查通常在 function 环境中设置的环境变量(我在我的例子中使用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
然后我在我的 package.json 准备脚本中使用它:
// ...
"prepare": "./scripts/prepare.sh",
// ...
可能有更好的解决方案,但这就是我让它为我工作的方式。 希望这可以帮助!
This SO answer is spot on and uses bash 脚本。 我使用答案中提到的相同概念在scripts/
文件夹中用 js 编写准备脚本,名称为prepare.mjs
"use-strict";
import * as path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Firebase sets the GOOGLE_FUNCTION_TARGET when running in the firebase environment
const isFirebase = process.env.GOOGLE_FUNCTION_TARGET !== undefined;
if (!isFirebase) {
process.chdir("../"); // path where .git file is present. In my case it was ..
const husky = await import("husky");
husky.install("functions/.husky"); // path where .husjy config file is present w.r.t. .git file
}
在我的package.json
中,我使用了上面的脚本如下
{
"name": "functions",
"scripts": {
"build": "tsc",
"start": "npm run serve",
"deploy": "firebase deploy --only functions",
"prepare": "node ./scripts/prepare.mjs"
}
"dependencies": {
"firebase-admin": "^11.4.1",
"firebase-functions": "^4.1.1",
},
"devDependencies": {
"husky": "^8.0.2",
"typescript": "^4.9.4"
}
}
这使用了谷歌在文档中记录的环境变量( GOOGLE_FUNCTION_TARGET
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.