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

如何配置package.json使仅Yarn可启动项目,npm start报错?

解决方案:限制项目仅通过Yarn启动

问题分析

原prestart脚本使用精确匹配判断$npm_config_user_agent是否等于"yarn",但Yarn实际运行时,该环境变量的值是包含Yarn版本、Node版本等信息的完整字符串(例如yarn/1.22.19 npm/? node/v18.17.0 darwin x64),而非单纯的"yarn",导致yarn start也被错误拦截。

修改后的Scripts配置

将prestart脚本改为字符串包含判断,即可实现仅拦截npm start,允许yarn start和yarn run dev正常运行:

"scripts": {
  "prestart": "case \"$npm_config_user_agent\" in yarn*) ;; *) echo \"Error: Use 'yarn start' to run this application\" && exit 1; esac",
  "start": "yarn run dev",
  "dev": "vite",
  "build": "vite build",
  "preview": "vite preview"
}

配置说明

  • prestart脚本通过case语句检测$npm_config_user_agent前缀:如果以yarn开头则跳过错误提示,否则输出错误信息并终止流程。
  • yarn run dev可直接执行,无前置脚本拦截,符合需求。
  • 若使用Bash环境,也可替换为正则匹配写法(效果一致):
    "prestart": "if [[ ! \"$npm_config_user_agent\" =~ yarn ]]; then echo \"Error: Use 'yarn start' to run this application\" && exit 1; fi",
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:02:07