Secara default, Yii2 akan mempublis asset-asset ke folder @web dengan menghash(mengencript) nama foldernya. Kita bisa mengubah behavior ini yaitu mempertahankan nama asli dari folder asset sebelum dipublis. Caranya dengan mengcustom fungsi hash bawaan assetManager.
Berikut caranya. Kita buat class behavior, lalu kita attach ke komponen assetManager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace app\classes; | |
| use Yii; | |
| use yii\base\Behavior; | |
| use yii\web\AssetManager; | |
| /** | |
| * Description of AssetPublishBehavior | |
| * | |
| * @author Misbahul D Munir <[email protected]> | |
| * @since 1.0 | |
| */ | |
| class AssetPublishBehavior extends Behavior | |
| { | |
| /** | |
| * sesuaikan kebutuhan | |
| */ | |
| public $maps = [ | |
| '@node_modules' => 'nm', | |
| '@vendor' => 'v', | |
| '@bower' => 'b', | |
| '@npm' => 'nm', | |
| '@app' => '', | |
| ]; | |
| protected $mapDirs = []; | |
| public function init() | |
| { | |
| foreach ($this->maps as $path => $to) { | |
| $path = rtrim(Yii::getAlias($path), '/') . '/'; | |
| $this->mapDirs[$path] = trim($to, '/'); | |
| } | |
| krsort($this->mapDirs); | |
| } | |
| /** | |
| * | |
| * @param AssetManager $owner | |
| */ | |
| public function attach($owner) | |
| { | |
| parent::attach($owner); | |
| $owner->hashCallback = [$this, 'hash']; | |
| } | |
| public function hash($path) | |
| { | |
| foreach ($this->mapDirs as $key => $to) { | |
| if (strpos($path, $key) === 0) { | |
| $subpath = substr($path, strlen($key)); | |
| return $to ? "$to/$subpath" : $subpath; | |
| } | |
| } | |
| return ltrim($path, '/'); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| return [ | |
| … | |
| 'components' => [ | |
| … | |
| 'assetManager' => [ | |
| 'as publish' => 'app\classes\AssetPublishBehavior' | |
| ] | |
| ], | |
| ]; |
