如何在 yii2 项目中包含 npm-asset 包?

How to include npm-asset packages inside yii2 project?

我已经在 yii2 中使用 Asset Packagist 成功安装了 npm-asset/socket.io 包及其依赖项。现在,我不能将它包含在我的页面中。我在 AppAsset.php 中试过这样:

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

没用:

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

然后,我尝试将该文件包含在视图文件中,如下所示:

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

它给了我这个错误:

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

我需要有关如何在视图文件中使用此 js 文件的帮助。

composer 安装的源代码放在 vendor 文件夹中,不能直接访问。您需要发布资产,然后包含已发布的资源。

为此,您可以为 socket.io 创建资产包,例如像这样

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'
    ];
}

然后在您的 AppAsset 包中将 SocketIoAsset 添加到 $depends 属性

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

现在因为你的AppAsset依赖于SocketIOAsset,SocketIOAsset::$sourcePath中定义的文件夹会在AppAsset注册时发布,SocketIOAsset::$js数组中的文件会被链接。