使用 Composer 在生产环境中安装 npm 和 bower 包(即没有 devDependencies)

2022-01-21 00:00:00 php laravel composer-php npm bower

在我的 composer.json 文件中,脚本部分有以下内容:

In my composer.json file I have the following in the scripts section:

    "post-install-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize",
        "npm install",
        "bower install"
    ]

运行composer install"时,这将导致 npm 和 bower 安装它们的所有依赖项,默认情况下包括 devDependencies.在进行生产部署时(例如,'composer install --no-dev' 我想启动 'npm install --production' 和 'bower install --production')

When running 'composer install' this will cause npm and bower to install all their dependencies, which by default include devDependencies. When it comes to doing a production rollout (e.g. 'composer install --no-dev' I want to fire up 'npm install --production' and 'bower install --production')

据我所知,似乎没有一种方法可以根据传递的标志更改为安装后命令"指定的列表,或者设置可以传递给的变量的方法post-install-cmd 中的命令.

As far as I can tell, there doesn't seem to be a way to either change the list specified for 'post-install-command' depending on flags passed, or a way of setting variables that can then be passed to commands in post-install-cmd.

我错过了什么吗?似乎不可能使用 composer 仅使用配置来进行开发和生产安装.我真的必须在生产中使用 composer install --no-scripts 然后自己手动运行所有四个命令吗?这似乎有点笨拙.

Am I missing something? It doesn't seem possible to use composer to do both a dev and production install using just the config. Do I really have to use composer install --no-scripts on production and then manually run all four of the commands myself? That seems a little clunky.

推荐答案

您可以随时使用 PHP 为您进行环境检测,然后从同一脚本安装其他依赖项.这不是很干净,就像在 post-install-cmd 中包含 npm 和 bower,但它会为您提供所需的内容.

You could always make use of PHP to do environment detection for you, then install other dependencies from the same script. This isn't nice and clean, like including npm and bower in post-install-cmd, but it will get you what you're looking for.

"post-install-cmd": [
     "php artisan clear-compiled",
     "php artisan optimize",
     "php path/to/installer.php"
 ]

示例安装程序.php:

Example installer.php:

// Logic to determine the environment. This could be determined many ways, and depends on how your
// application's environment is determined. If you're making use of Laravel's environment
// capabilities, you could do the following:
$env = trim(exec('php artisan env'));

// Clean up response to get the value we actually want
$env = substr($env, strrpos($env, ' ') + 1);

$envFlag = ($env === 'production')
    ? '--production'
    : '';

// Install npm
passthru("npm install {$envFlag}");
// Install bower
passthru("bower install {$envFlag}");

您可以使这个示例更加健壮,甚至为它创建一个 Artisan 命令.

You could make this example more robust, and even create an Artisan command for it.

相关文章