composer archive命令根本不存在,执行必报错“command 'archive' is not defined”;正确做法是先运行composer install --no-dev --optimize-autoloader,再用git archive或zip打包,并通过.gitattributes精确排除无关文件。

composer archive 命令根本不存在
执行 composer archive 必报错:Command "archive" is not defined。这不是你装错了、没升级,也不是环境问题——Composer 2.0 起就彻底移除了这个命令,2.2+ 所有稳定版均不支持。所有声称“直接运行就能打包”的教程,要么混淆了 git archive,要么依赖了第三方 bin 工具(如 vendor/bin/composer-archive),不是 Composer 自带能力。
真正可用的归档路径只有两步
生产环境可部署的包,必须满足两个硬条件:vendor 已安装且精简、源码已过滤无关内容。绕不开这一步:
- 先运行
composer install --no-dev --optimize-autoloader:跳过require-dev包,生成优化后的autoload_classmap.php,避免运行时扫描 - 再用
git archive或系统zip打源码包:它只打包 Git 已跟踪的文件,天然不含.git/、node_modules/、未提交的.env - 必须带上
composer.lock:否则目标机器composer install无法复现依赖版本
.gitattributes 是控制打包内容的唯一可靠方式
想让 git archive(或 Packagist 自动生成 dist 包)排除 tests/、examples/、.md 等,不能靠 archive.exclude——它只在极少数私有 CI 流程中生效,Packagist 和 GitHub Releases 完全不认。
-
.gitattributes是 Git 原生命令,git archive严格按它执行,优先级最高 - 规则必须写绝对路径(从仓库根起):
/tests/ export-ignore有效,tests/无效 - 每行一个规则,不支持嵌套通配符:
/src/**/tests不生效,**/tests也不被识别 - 验证方法:本地跑
git archive --format=zip --output=test.zip HEAD,解压后检查是否干净
别以为 --no-dev 就万事大吉
--no-dev 只影响 vendor/ 目录,对项目根目录下的 tests/、docs/、.env.example 完全无感。这些文件仍会打进 zip,可能泄露敏感信息或干扰部署流程。
- 必须显式用
.gitattributes排除,或在zip命令里加-x参数(如zip -r app.zip . -x "tests/*" -x "docs/*") - Windows 用户慎用 CMD 自带
zip:不支持-x,请用 Git Bash 或 WSL - 自动化打包建议写进
composer.json的scripts,例如:"package": ["@composer install --no-dev --optimize-autoloader", "git archive --format=zip --output=dist.zip HEAD"]
.gitattributes 是否已提交到 Git 历史——如果只是新建但没 git add 和 git commit,git archive 根本看不到它。











