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

如何在webpack的NPM脚本中检查文件存在后再执行目标脚本

报错原因

npm 默认在 Windows 环境下会使用 cmd 作为脚本执行器,你写的 Test-Path 是 PowerShell 专属语法,cmd 无法识别,因此执行时报错。你直接在 PowerShell 终端运行命令正常,就是因为终端环境用的是 PowerShell 而非 cmd。

解决方法

方法1:修改npm脚本执行器为PowerShell

如果你仅在本地开发、且只用PowerShell环境,可以直接修改npm的全局配置,指定脚本用PowerShell执行:

# 用PowerShell 5.x的情况
npm config set script-shell powershell

# 用PowerShell 7+的情况
npm config set script-shell pwsh

如果只想对当前项目生效,可以在项目根目录新建 .npmrc 文件,添加如下内容即可:

script-shell=powershell

方法2:使用跨平台兼容的Node脚本实现(推荐)

该方法无需修改npm配置,兼容Windows、Mac、Linux所有环境,适合团队协作场景:

  1. 项目根目录新建 check-postdev.js 文件,内容如下:
const fs = require('fs')
const { execSync } = require('child_process')

if (fs.existsSync('./postdev.sh')) {
  console.log('file exists')
  execSync('./postdev.sh', { stdio: 'inherit' })
}
  1. 修改package.json里的postdev配置:
"postdev": "node check-postdev.js"

方法3:类Unix环境通用写法

如果你仅在Mac/Linux环境、或者Windows使用Git Bash,也可以直接用bash语法写判断:

"postdev": "test -f ./postdev.sh && echo 'file exists' && ./postdev.sh"

内容的提问来源于stack exchange,提问作者G. Goncharov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:06:02