Composer中的scripts脚本如何使用?(自动化任务配置)

admin 百科 14
Composer 的 scripts 是 composer.json 中定义的命令别名,用于执行代码检查、测试等自动化任务,支持字符串、数组及 PHP 回调形式,并可在生命周期事件(如 post-install-cmd)中自动触发或手动运行。

Composer中的scripts脚本如何使用?(自动化任务配置)-第1张图片-佛山资讯网

Composer 的 scripts 是在 composer.json 中定义的一组命令别名,用于快速执行项目相关的自动化任务,比如代码检查、测试、构建、清理等。它不依赖外部任务管理工具(如 Make 或 npm scripts),开箱即用,且能跨平台运行。

如何定义 scripts

composer.jsonscripts 字段下,以键值对形式声明脚本名称和对应命令:

  • 键是自定义的脚本名(如 testcs-check
  • 值可以是字符串(单条命令)、字符串数组(按顺序执行多条命令),或指向 PHP 方法的回调(格式:"Vendor\Class::method"

示例:

"scripts": {
  "test": ["phpunit --colors=always", "phpstan analyse src/"],
  "cs-check": "php-cs-fixer check src/",
  "post-install-cmd": "MyApp\Script::onInstall"
}

登录后复制

常用触发时机(事件脚本)

Composer 在执行某些生命周期操作时会自动运行对应名称的脚本,无需手动调用。常见内置事件包括:

  • pre-install-cmd:运行 composer install
  • post-install-cmd:运行 composer install 后(含首次安装)
  • pre-update-cmd:运行 composer update
  • post-update-cmd:运行 composer update
  • post-autoload-dump:自动加载文件生成后(如修改了 autoload 配置)

这些事件适合做环境初始化、缓存清除、配置生成等操作。

如何手动运行 scripts

使用 composer run(推荐,Composer 2.2+)或兼容写法 composer run-script

标签: php js json composer npm app 工具 键值对 字符串数组

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~