scripts是composer.json中用于定义自动化脚本的字段,支持在安装、更新等事件触发时执行命令或PHP方法,可用于初始化项目、清空缓存等任务。

Composer 的 scripts 功能允许你在执行 Composer 命令时自动运行自定义脚本,比如在安装、更新、卸载包时触发某些操作。它非常适用于自动化项目初始化、测试运行、代码检查、清理缓存等任务。
在 composer.json 文件中,scripts 是一个可选的字段,用于定义一系列命名的脚本(可以是 PHP 脚本、命令行指令或类方法)。这些脚本会在特定事件发生时被触发,也可以通过
composer run [script-name]
Composer 支持多种内置事件,可以在对应阶段自动执行脚本:
install
install
update
update
create-project
你可以在
composer.json
1. 直接写 shell 命令
"scripts": { "post-update-cmd": "php artisan clear-compiled", "post-install-cmd": "echo 'Installation finished.'" }2. 执行多个命令(数组形式)
"scripts": { "post-update-cmd": [ "php artisan config:clear", "php artisan route:clear", "php artisan view:clear" ] }3. 调用 PHP 类的静态方法(推荐用于复杂逻辑)
"scripts": { "post-create-project-cmd": [ "My\Project\Installer::postCreateProject" ] }对应的 PHP 类需要能被自动加载(通常放在
src/
你可以通过
composer run
前提是已经定义了名为
my-script
Laravel 项目清空缓存
"scripts": { "post-update-cmd": [ "Illuminate\Foundation\ComposerScripts::postUpdate", "@php artisan config:cache", "@php artisan route:cache" ], "post-autoload-dump": [ "php artisan event:clear" ] }初始化项目配置
"scripts": { "post-create-project-cmd": [ "php bin/init.php" ] }比如
bin/init.php
以上就是Composer脚本scripts如何使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号