How to use a package from vendor/bower-asset

I’ve been developing a Yii2 project these days and I want to use the dropzone.js library. I haven’t searched for any extensions that integrate it and I’d like to use it “vanilla”. So, I’ve installed bower-asset/dropzone in my app dir with composer. Now, I’m puzzled about how to use it. I suppose I have to create a custom asset class that injects the library inside the view (css, js files, etc.).

Are there any examples of code I can look at for such a case like this?

Create and Asset Bundle class to publish dropzone.js. Here is an example:

<?php

namespace marqu3s\summernote;

use Yii;
use yii\web\AssetBundle;

class SummernoteAsset extends AssetBundle
{
    /** @var string */
    public $sourcePath = '@bower/summernote/dist';

    /** @var array */
    public $depends = [
        'yii\bootstrap\BootstrapPluginAsset',
    ];

    /**
     * @inheritdoc
     */
    public function init()
    {
        $postfix = YII_DEBUG ? '' : '.min';

        if (isset(Yii::$app->params['bsVersion']) && Yii::$app->params['bsVersion'] == 4) {
            $this->depends = ['yii\bootstrap4\BootstrapPluginAsset'];
            $this->css[] = 'summernote-bs4.css';
            $this->js[] = 'summernote-bs4' . $postfix . '.js';
        } else {
            $this->depends = ['yii\bootstrap\BootstrapPluginAsset'];
            $this->css[] = 'summernote.css';
            $this->js[] = 'summernote' . $postfix . '.js';
        }

        parent::init();
    }
}

Notice the use of the alias @bower.
Take a look here to check the predefined aliases.
Key Concepts: Aliases | The Definitive Guide to Yii 2.0 | Yii PHP Framework (yiiframework.com)

Then add it to your layout or view like this:

use marqu3s\summernote\SummernoteAsset;

SummernoteAsset::register($this);

It will publish the javascript and css files (assets) to a web accessible folder and register them in the resulting html code.

1 Like