Is there a way to force Yii to reload module asset

2019-04-04 15:34发布

问题:

My website is divided into separate modules. Every module has it's own specific css or js files in /protected/modules/my_module/assets/css or js for js files. Yiis assets manager creates folder when I first use page that uses my assets. Unfortunately if I change sth in my files - Yii does not reload my css or js file. I have to manually delete /projects/assets folder. It is really annoying when you are developing the app.

Is there a way to force Yii to reload assets every request?

回答1:

In components/Controller.php add the following (or adjust an existing beforeAction):

protected function beforeAction($action){
    if(defined('YII_DEBUG') && YII_DEBUG){
        Yii::app()->assetManager->forceCopy = true;
    }
    return parent::beforeAction($action);
}

What this does it that before any actions are started, the application will check to see if you are in debug mode, and if so, will set the asset manager to forcibly recopy all the assets on every page load.

See: http://www.yiiframework.com/doc/api/1.1/CAssetManager#forceCopy-detail

I have not tested this, but based on the documentation I believe it should work fine.

Note: The placement of this code within beforeAction is just an example of where to put it. You simply need to set the forceCopy property to true before any calls to publish(), and placing it in beforeAction should accomplish that goal.



回答2:

If you're using Yii2 there is a much simpler solution through configuration.

Add the following to your 'config/web.php':

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    // ...
    $config['components']['assetManager']['forceCopy'] = true;
}

This forces the AssetManager to copy all folders on each run.



回答3:

An alternatively solution is to publish your module assets like this:

Yii::app()->assetManager->publish($path, false, -1, YII_DEBUG);

The fourth parameter enforces a copy of your assets, even if they where already published. See the manual on publish() for details.



回答4:

Re-publishing assets on every request potentially takes a lot of resources and is unnessecary for development.

  • For development, it's much easier to use the linkAssets feature of CClientScript. Assets are published as symbolic link directories, and never have to be regenerated. See: http://www.yiiframework.com/doc/api/1.1/CAssetManager#linkAssets-detail

  • For staging/production, you should make clearing the assets/ folder part of your update routine/script.

Only fall back to one of the other solutions if for some reason you cannot use symbolic links on your development machine (not very likely).



回答5:

In YII 1 in config we have:

'components'=> [
...
 'assetManager' => array(
            'forceCopy' => YII_DEBUG,
...
)
...

]