Search code examples
yii2assets

How to include npm-asset packages inside yii2 project?


I have successfully installed npm-asset/socket.io package and its dependencies by using Asset Packagist in yii2. Now, I cannot include it in my pages. I tried in AppAsset.php like this:

public $js = ['@npm/socket.io/client-dist/socket.io.js'];

it did not work:

GET http://project.localhost/@npm/socket.io/client-dist/socket.io.js net::ERR_ABORTED 404 (Not Found)

Then, I tried to include that file inside view file like this:

<script src="<?php echo Yii::getAlias('@npm').'/socket.io/client-dist/socket.io.js' ?>"></script>

it gave me this error :

Not allowed to load local resource: file:///C:/Projects_folder/Php/Yii2/project/vendor/npm-asset/socket.io/client-dist/socket.io.js

I need help with how to use this js file inside view files.


Solution

  • The sources installed by composer are placed in vendor folder which is not directly accessible. You need to publish the assets and then include the published resources.

    To do that you can make an asset bundle for socket.io for example like this

    namespace app\assets;
    
    use yii\web\AssetBundle;
    
    class SocketIOAsset extends AssetBundle
    {
        //this is path where source files that needs publishing are located
        public $sourcePath = "@npm/socket.io/client-dist";
        public $css = [
        ];
        public $js = [
            'socket.io.js'
        ];
    }
    

    Then in your AppAsset bundle add the SocketIoAsset into $depends property

    class AppAsset extends AssetBundle
    {
        public $basePath = '@webroot';
        public $baseUrl = '@web';
        
        public $depends = [
            SocketIOAsset::class,
            // ... other dependencies ...
        ];
        // ... other definitions ...
    }
    

    Now because your AppAsset depends on SocketIOAsset, the folder defined in SocketIOAsset::$sourcePath will be published when AppAsset is registered, and files in SocketIOAsset::$js array will be linked.