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.

1 Like

Check this post: Getting Started: Assets Setup | Twitter Bootstrap Extension for Yii 2 | Yii PHP Framework

And see if any of your other configs are missing.

Keep in mind that in your Asset config, the @alias attribute should be used in the $basePath class variable, while the alias must be properly configured.

For more detailed explanation in assets, you can read this article: Yii2 Assets

1 Like

thank you)

My solution:

I have created a separate class for the specific package like this:

namespace app\assets;
use yii\web\AssetBundle;


class SocketIOAsset extends AssetBundle
{
    public $sourcePath = "@npm/socket.io-client/dist";
    public $css = [];
    public $js = [
        'socket.io.js'
    ];
}

and then called in main assets file
public $depends = [
‘yii\web\YiiAsset’,
‘yii\bootstrap\BootstrapAsset’,
SocketIOAsset::class
];

More info:

2 Likes