Home > other >  Yii2 CSS to asset folder
Yii2 CSS to asset folder

Time:06-19

I have my site.css in my web/css/

which i declared here

namespace frontend\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.min.css'
    ];
}

How do i get AssetBundle to copy it into the assets folder to make it look like this

<link href="/frontend/web/assets/2edj2hj2jk/css/site.css" rel="stylesheet">

instead of this?

<link href="/frontend/web/css/site.css" rel="stylesheet">

or is there another way to achieve this? Basically I want everything in web/css, web/images and web/js to be saved in the assets folder

CodePudding user response:

If you really want to have those resources copied into /web/assets folder than all you need to do is use $sourcePath property instead of $basePath and @baseUrl properties.

You should move your images, css and js folder somewhere else from web folder because AssetManager will copy the whole content of folder referenced in $sourcePath.

Let's say you move it into frontend/resources.

namespace frontend\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
    public $sourcePath = '@frontend/resources';
    public $css = [
        'css/site.min.css'
    ];
}

But in fact you shouldn't do this. AssetManager copies resources into web/assets folder to allow direct access to files that wouldn't be normally accessible because they are hidden in widgets, modules or vendor folder. If your resource files are already in web folder which is exposed by web server then there is no need to copy them elsewhere.

You will even make it harder to reference images from your view files, because the name of hash subfolder of web/assets folder is not fixed and it can change when your resource files changes.

  • Related