Yii2 Asset Bundles & Asset Management

Introduction

Asset management in Yii2 helps developers efficiently manage JavaScript, CSS, images, and other frontend resources. Yii2 introduces the Asset Bundle concept, which allows grouping related assets and controlling their dependencies.

This tutorial covers:

  • What Asset Bundles are
  • How to create and register Asset Bundles
  • Dependency Management in Asset Bundles
  • Publishing assets
  • Using Asset Bundles in Modules
  • Customizing asset paths and versions
  • Performance considerations

What is an Asset Bundle?

An Asset Bundle in Yii2 is a collection of frontend assets like CSS, JS, and images. These bundles are registered in views and automatically published to the web/assets directory when requested.

Yii2 uses yii\web\AssetBundle as the base class for defining an asset bundle.

Default Asset Bundles in Yii2

Yii2 provides several default asset bundles:

  • yii\web\YiiAsset – Includes Yii's JavaScript framework
  • yiiootstrap5\BootstrapAsset – Loads Bootstrap 5 CSS
  • yiiootstrap5\BootstrapPluginAsset – Loads Bootstrap 5 JS

Creating an Asset Bundle

To create an Asset Bundle, extend yii\web\AssetBundle.

Example: Creating AppAsset

Create assets/AppAsset.php:

namespace app\assets;

use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
        'js/site.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yiiootstrap5\BootstrapAsset',
    ];
}

Explanation

  • $basePath: The directory where assets are located.
  • $baseUrl: The URL path of the assets.
  • $css: List of CSS files.
  • $js: List of JavaScript files.
  • $depends: Other asset bundles this bundle depends on.

Registering Asset Bundles in Views

To include the AppAsset bundle in a view file, register it like this:

use app\assets\AppAsset;

AppAsset::register($this);

This will include the CSS and JS files from AppAsset in the HTML output.


Dependency Management

Dependencies ensure required CSS and JS files are loaded in the correct order.

For example, if your script requires jQuery, you should depend on yii\web\JqueryAsset:

public $depends = [
    'yii\web\JqueryAsset',
];

Yii will automatically include jQuery before your script.


Asset Publishing

Yii2 publishes assets when they are located outside the web root.

Example: Suppose your assets are inside @app/widgets/assets, they will be copied to web/assets when requested.

You can force publishing:

$this->registerAssetBundle(AppAsset::className(), yii\web\View::POS_HEAD);

Custom Publishing Options

You can customize how assets are published using publishOptions:

public $publishOptions = [
    'forceCopy' => false,
];
  • When forceCopy is true: Assets will be re-published on every request, useful for development.
  • When forceCopy is false: Assets are only published once, improving performance in production.

Asset Bundles in Modules

Each module can have its own Asset Bundle.

Example: Define ModuleAsset in modules/admin/assets/ModuleAsset.php:

namespace app\modules\admin\assets;

use yii\web\AssetBundle;

class ModuleAsset extends AssetBundle
{
    public $sourcePath = '@app/modules/admin/assets';
    public $css = ['admin.css'];
    public $js = ['admin.js'];
    public $depends = ['yii\web\YiiAsset'];
}

Register it in the module’s layout:

use app\modules\admin\assets\ModuleAsset;
ModuleAsset::register($this);

Using Separate Views & Layouts in Modules

To use custom views for a module:

\Yii::$app->view->theme = new \yii\base\Theme([
    'pathMap' => ['@app/views' => '@app/modules/admin/views'],
]);

Customizing Asset Paths and Versions

To set versioning, use AssetManager::$appendTimestamp in the application config:

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

This appends timestamps to asset URLs (site.css?v=1610000000), forcing the browser to reload updated files.

For external assets:

public $js = [
    'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js',
];

You can also specify where scripts should be loaded using jsOptions:

public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
  • POS_HEAD: Loads the script in the <head> section.
  • POS_BEGIN: Loads the script at the beginning of <body>.
  • POS_END: Loads the script at the end of <body> (recommended for performance).

Performance Considerations

  • Use AssetManager::$appendTimestamp to prevent caching issues.
  • Combine and minify assets using AssetManager::bundles.
  • Avoid forceCopy = true in production to prevent unnecessary re-publishing.
  • Load JS files at POS_END for better page load speed.

Conclusion

Yii2's Asset Management simplifies frontend asset handling, ensuring efficient loading and dependency management. Asset Bundles help organize and optimize JavaScript and CSS files, making the application modular and scalable.