Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: How can I add an JavaScript library via composer?

I have setup a basic app according to this guide (Installing Yii). This is no problem. According to the guide I have also added fxp/composer-asset-plugin globally to composer.phar. Also no problem.

Now I've got the requirement to work with q.js which is hosted* as npm package. But I don't know how to add it via composer. I know I could probably use a CDN instead or download and store it manually. But I prefer using composer. So what do I have to do to make this work?

I have added this to my composer.json:

"require": {
    "php": ">=5.4.0",
    "yiisoft/yii2": ">=2.0.4",
    "yiisoft/yii2-bootstrap": "*",
    "yiisoft/yii2-swiftmailer": "*",
    "npm-asset/q": "~1.4"               <------
},

and called composer.phar update but got the exception:

Your requirements could not be resolved to an installable set of packages.

    Problem 1
    - The requested package npm-asset/q could not be found in any version, 
      there may be a typo in the package name.

Is it a wrong approach?

I'd like to know in general how to add JS libraries to the project. I just know that I have to add it later to an Asset as well, but currently I'm not able to get the JS file in the first place.

* Is hosted the correct term?

like image 826
robsch Avatar asked Jun 17 '15 10:06

robsch


People also ask

How to register js in Yii2?

In Yii2, the way to register JS script into view is using \yii\web\View::registerJS(), For example, if you want to initialize a jQuery plugin, you do: // in view file <div class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <p>Hello World!

What is composer in Yii2?

Composer is a tool for dependency management in PHP. Yii2 uses it to install itself and other vendors' modules (for example, bootstrap). It is also possible to install Yii2 in the old way, by downloading the complete package and transferring it to the host, local or remote, where the framework will be installed.


1 Answers

Currently the easiest way to require npm or bower package in composer.json is to use asset-packagist:

  1. Remove fxp/composer-asset-plugin:

    composer global remove fxp/composer-asset-plugin
    
  2. Add repository to your composer.json:

    "repositories": [
        {
            "type": "composer",
            "url": "https://asset-packagist.org"
        }
    ]
    

Then you should be able to require npm package with npm-asset/ prefix and bower package with bower-asset/ prefix in composer.json:

"require": {
    "bower-asset/bootstrap": "^3.3",
    "npm-asset/jquery": "^2.2"
}

No need for global plugin and much faster composer updates.

like image 147
rob006 Avatar answered Oct 11 '22 02:10

rob006