Yii2 资产 - 子资源完整性

Yii2 Assets - Sub-Resource Integrity

我正在处理我所有的 Yii2 资产包以合并子资源完整性。所以现在我有...

namespace some\amazing\space;

class AmazingAsset extends AssetBundle
{
    public $sourcePath = 'path/to/asset/files'; // or
    public $baseUrl = '//url/to/asset/files';
    public $js = [
        'js/amazingscript.min.js',
    ];
    public $jsOptions = [
        'integrity' => 'hash-of-js/amazingscript.min.js';
        'crossorigin' => 'anonymous',
    ];
    public $depends = [
        'some\useful\ThingAsset',
    ];
}

现在我想在我的捆绑包中添加一些更神奇的调味料并获得...

namespace some\amazing\space;

class MoreAmazingAsset extends AssetBundle
{
    public $sourcePath = 'path/to/asset/files'; // or
    public $baseUrl = '//url/to/asset/files';
    public $js = [
        'js/amazingscript.min.js',
        'js/moreamazingscript.min.js',
    ];
    public $jsOptions = [
        'integrity' => 'hash-of-js/amazingscript.min.js';
        'crossorigin' => 'anonymous',
    ];
    public $depends = [
        'some\useful\ThingAsset',
    ];
}

但在这里我卡住了,因为 jsOptions 将应用于两个 .js 文件。我能看到的唯一方法是将其分成 2 个包,一个需要另一个包...

namespace some\amazing\space;

class MoreAmazingAsset extends AssetBundle
{
    public $sourcePath = 'path/to/asset/files'; // or
    public $baseUrl = '//url/to/asset/files';
    public $js = [
        'js/moreamazingscript.min.js',
    ];
    public $jsOptions = [
        'integrity' => 'hash-of-js/moreamazingscript.min.js';
        'crossorigin' => 'anonymous',
    ];
    public $depends = [
        'some\amazing\space\AmazingAsset',
    ];
}

然后...

namespace some\amazing\space;

class AmazingAsset extends AssetBundle
{
    public $sourcePath = 'path/to/asset/files'; // or
    public $baseUrl = '//url/to/asset/files';
    public $js = [
        'js/amazingscript.min.js',
    ];
    public $jsOptions = [
        'integrity' => 'hash-of-js/amazingscript.min.js';
        'crossorigin' => 'anonymous',
    ];
    public $depends = [
        'some\useful\ThingAsset',
    ];
}

还有其他选择吗?

据我了解,您希望能够分别为 2 个 js 文件的 integrity 属性指定散列,目前通过使用 $jsOptions 提供相同的散列对于所有脚本文件。

如果以上内容正确,您可以通过将源指定为数组来指定 $js 中的属性,如下所示。而不是为它们创建 2 个单独的 AssetBundles

public $js = [
        ['js/some.js','integrity'=>'SOME_SHA_HASH' ],
        ['js/another.js','integrity'=>'ANOTHER_SHA_HASH' ],
    ];

记住

"The hash algorithm must be one of sha256, sha384, or sha512, followed by a '-' character."

您的代码如下所示

namespace some\amazing\space;

class CombinedAmazingAsset extends AssetBundle
{
    public $sourcePath = 'path/to/asset/files'; // or
    public $baseUrl = '//url/to/asset/files';
    public $js = [
        ['js/amazingscript.min.js','integrity' => 'hash-of-js/amazingscript.min.js'],
        ['js/moreamazingscript.min.js','integrity' => 'hash-of-js/moreamazingscript.min.js'],
    ];
    public $jsOptions = [
        'crossorigin' => 'anonymous',
    ];
    public $depends = [
        'some\useful\ThingAsset',
    ];
}