You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust Trunk在PowerShell中无法读取环境变量问题求助

Trunk钩子中PowerShell环境变量解析失败的解决方法

问题重现

配置Trunk构建钩子时,最初参考教程使用sh执行:

[[hooks]]
stage = "build"
command = "sh"
command_arguments = ["-c", "tailwind -i ./src/tailwind.css -o $TRUNK_STAGING_DIR/tailwind.css"]

由于Windows环境无sh,改为直接调用tailwindcss CLI:

[[hooks]]
stage = "build"
command = "tailwindcss"
command_arguments = ["-i", "./src/tailwind.css", "-o", "$TRUNK_STAGING_DIR/tailwind.css"]

执行后生成了名为$TRUNK_STAGING_DIR的文件夹而非正确的暂存目录。尝试用PowerShell变量语法$($env:TRUNK_STAGING_DIR):

[[hooks]]
stage = "build"
command = "tailwindcss"
command_arguments = ["-i", "./src/tailwind.css", "-o", "$($env:TRUNK_STAGING_DIR)/tailwind.css"]

出现错误:

[Error: ENOENT: no such file or directory, mkdir 'C:\project_path\$($Env:TRUNK_STAGING_DIR)'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'mkdir',
  path: 'C:\\project_path\\$($Env:TRUNK_STAGING_DIR)'
}

原因分析

这不是Trunk或tailwindcss的Bug,而是环境变量解析逻辑导致的:

  • 原sh -c配置中,$TRUNK_STAGING_DIR由Shell(sh)负责解析为环境变量值;
  • 直接调用tailwindcss时,command_arguments中的参数会被当作字面量传递,PowerShell不会自动解析参数里的变量语法;
  • 单独使用$($env:TRUNK_STAGING_DIR)时,Trunk的配置文件不识别PowerShell的变量语法,因此变量名被直接作为路径使用。

解决方案

以下两种方法可解决问题:

方法1:通过PowerShell执行命令

利用powershell -c让PowerShell负责解析环境变量,再调用tailwindcss:

[[hooks]]
stage = "build"
command = "powershell"
command_arguments = ["-Command", "tailwindcss -i ./src/tailwind.css -o $env:TRUNK_STAGING_DIR/tailwind.css"]

这里-Command参数会让PowerShell解析$env:TRUNK_STAGING_DIR为实际环境变量值,再执行tailwindcss命令。

方法2:编写PowerShell脚本调用

创建一个build-tailwind.ps1脚本:

tailwindcss -i ./src/tailwind.css -o "$env:TRUNK_STAGING_DIR/tailwind.css"

然后在Trunk钩子中调用该脚本:

[[hooks]]
stage = "build"
command = "powershell"
command_arguments = ["-File", "./build-tailwind.ps1"]

这种方式更适合复杂的构建逻辑,也便于调试。

内容的提问来源于stack exchange,提问作者ApolloRoboto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 10:52:02