Search code examples
yii2assets

Yii2 AssetBundle publishOptions pattern syntax?


Might be stupid, but just wanted to ask if the syntax I'm using is correct when publishing asset's files. The Guide instructs to use folder names without trailing asterisk, however for me it does not work that way.

The weird thing is even if I specify to only publish css and images folder, the assetManager also publishes other folders in $sourcePath (luckily without files inside). What's more, when new files are added to images folder, they remain unpublished until I delete @web/assets folder. Is this to be expected?

<?php
namespace app\views\layouts\main\assets;
use yii\web\AssetBundle;

class ThemeAsset extends AssetBundle
{
    public $sourcePath = '@theme';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];

    public $publishOptions = [
        "only" => [
            "css/*",
            "images/*",
        ],
        "forceCopy" => false,
    ];
}

Solution

  • The first note that you should set $sourcePath or $baseUrl not both of them (If you set the both, the former overwrites the last when assetManager calls publish method).

    The weird thing is even if I specify to only publish css and images folder, the assetManager also publishes other folders in $sourcePath (luckily without files inside).

    If you wanna avoid asset manager to publish this folders, you must mention them on except parameter of publisOptions:

    'except' => [
        "doc/",
        "img/",
    ],
    

    What's more, when new files are added to images folder, they remain unpublished until I delete @web/assets folder. Is this to be expected?

    Yes! It's a natural behavior. You may set forceCopy property of publishOptions to true in development mode. This causes to update asset contents in each refresh. Easily you can use Yii production constant: YII_DEBUG.

    public $publishOptions = [
        'only' => [
            'js/',
            'css/',
        ],
        'forceCopy' => YII_DEBUG,
    ];
    

    So totally you have an asset manager like this:

    <?php
    namespace app\views\layouts\main\assets;
    use yii\web\AssetBundle;
    
    class ThemeAsset extends AssetBundle
    {
        public $sourcePath = '@theme';
    
        public $css = [
            'css/site.css',
        ];
    
        public $publishOptions = [
            "only" => [
                "css/*",
                "images/*",
            ],
            'except' => [
                "doc/",
                "img/",
            ],
            "forceCopy" => YII_DEBUG,
        ];
    }