appendTimestamp 和 registerAssetBundle

appendTimestamp and registerAssetBundle

我正在使用以下配置通过资产管理器在资产路径中添加时间戳。

'assetManager' => [
      'appendTimestamp' => true,

appAsset.php

class AppAsset extends AssetBundle
{   
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        '/css/style.css'
    ];
}

可见

AppAsset::register($this);

但是在 html 我仍然看到 '/css/style.css' 没有时间戳。

我看到了解决方案 https://github.com/yiisoft/yii2/issues/9101#issuecomment-267274327

$file = '/css/style.css';
$asset = new \yii\web\AssetBundle(
    [
        'js' => [ltrim($file, '/')],
        'basePath' => '@webroot',
        'baseUrl' => '/'
    ]
);
$this->getAssetManager()->bundles[$file] = $asset;
$this->registerAssetBundle($file);

这个例子是可行的。 '/css/style.css?v=12557565'

是否有任何不在视图文件中写入 registerAssetBundle() 的方法?

首先,什么是public $sourcePath = '@frontend/assets';?这不是正确的路径,该路径实际上包含您的 Asset.php 文件,而不是源文件。根据文档

sourcePath: specifies the root directory that contains the asset files in this bundle. This property should be set if the root directory is not Web accessible. Otherwise, you should set the basePath property and baseUrl, instead. Path aliases can be used here.

只需将您的 .css 文件放在 frontend/web/css 下,将 .js 放在 frontend/web/js 下,然后删除 sourcePath 您不需要的文件,因为查看您的代码,只有在 frontend/themes/basic 下有源文件的情况下,您才会像 public $sourcePath = '@frontend/themes/basic/'; 一样使用 sourcePath,因为此路径不在 web 可访问目录

并添加时间戳 除了在 assetManagercomponents 部分下添加 appendTimestamp 选项外,您无需执行任何其他操作,确保添加 assetManager 在组件下。它将自动开始添加 ?v=125453612 与所有 CSSjs 文件

你的AppAsset.php

class AppAsset extends AssetBundle
{   
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/style.css'
    ];
}

frontend/config/main.php

'components' => [
..........
..........
    'assetManager' => [
        'appendTimestamp' => true
    ]
..........
..........
],

您的文件将开始看起来像这样

如果您想查看源代码,我可以向您展示同一站点的实例


编辑

当您提供源代码屏幕截图并查看您的代码时,我可以看出您在文件中使用了尾部斜杠 /,请从源文件路径中删除尾部斜杠,我也忽略了它乍一看,然后查看代码,我找不到任何其他可能是错误的东西。他们应该是这样的

'css/new.css',
'css/new2.css',

js 文件也一样。

尝试在 public $csspublic $js 中不使用第一个斜杠("js/.." 而是“/js/..”)。