Minimize js and css in custom path yii2 framework

In yii2 we have a lots of css and js files registered to pages. So it will take time to load all files one by one. we have to compress and combine all CSS files into a single file and do the same with JavaScript files.As a result, we serve just two files instead of the whole bunch one for css and other for js. Yii2 has, however, got the helper console command that you can use to simplify the process of compressing your assets and wiring them to your application. The most beautiful part is that you will not need to change any of your view files; all existing *Asset::register() calls can stay the same.

Minimize js and css in custom path in Yii2


The overall idea behind asset compiling in Yii is that you prepare a special asset bundle with just two files: one containing all of the compiled CSS and the other containing all of the compiled JavaScript.
Then, you override the configuration for asset bundles using the components.assetManager.bundles setting (read about it in the documentation) telling Yii to use this special, newly-created asset bundle instead of all of the usual bundles.

The \yii\console\controllers\AssetController class, which provides you with the ./yii asset command, encapsulates and automates the procedure of asset compilation. It even deals with the issue of files referenced from the CSS code for you, which is really amazing.

Before starting to compress the files we have to need yuicompressor.jar and Google Closure compiler should be named compiler.jar.After downloading these two files create a folder named tool(you can change the name also) in root of your project and move both files in this folder. 


After that, we need to create a special configuration file for the compressor. Yii has the console command to help you make a boilerplate template for this configuration. Run the following at the root of code base:


./yii asset/template frontend/web/config.php

After running this command you can see the new file in frontend/web directory.you should see the following code in config.php.

<?php
/**
 * Configuration file for the "yii asset" console command.
 */

// In the console environment, some path aliases may not exist. Please define these:
 Yii::setAlias('@webroot', __DIR__ . '/../web');
 Yii::setAlias('@web', '/');

return [
    // Adjust command/callback for JavaScript files compressing:
    'jsCompressor' => 'java -jar tool/compiler.jar --js {from} --js_output_file {to}',
    // Adjust command/callback for CSS files compressing:
    'cssCompressor' => 'java -jar tool/yuicompressor.jar --type css {from} -o {to}',
    // The list of asset bundles to compress:
    'bundles' => [
         'frontend\assets\main\MyAsset',         'frontend\assets\main\AnotherAsset'        // 'yii\web\YiiAsset',
        // 'yii\web\JqueryAsset',
    ],
    // Asset bundle for compression output:
    'targets' => [
        'myAsset' => [
            'class' => 'yii\web\AssetBundle',
            'basePath' => '@webroot',
            'baseUrl' => '/',
            'js' => 'compress/my-compressed.js',
            'css' => 'compress/my-compressed.css',
            'depends' => [
                'frontend\assets\main\MyAsset'
            ],
        ],
        'anotherAsset' => [
            'class' => 'yii\web\AssetBundle',
            'basePath' => '@webroot',
            'baseUrl' => '/',
            'js' => 'compress/another-compressed.js',
            'css' => 'compress/another-compressed.css',
            'depends' => [
                'frontend\assets\main\AnotherAsset'
            ],
        ],
    ],
    // Asset manager configuration:
    'assetManager' => [
  'basePath' => __DIR__,
        'baseUrl' => '',
        'bundles' => [
            'yii\web\JqueryAsset' => [
               'sourcePath' => null,
               'basePath' => null,
               'js' => ['']
            ]
        ]
    ],
];


The first part of the code is quite simple you should define the list of asset bundles you want to compress together. Note that they are named by their fully qualified names.Please specify the fully qualified names of asset bundles without the leading slashes. otherwise, you will break the mechanics.

In bundles includes the list of your assets . if you have to minified multiple assets the mention all the files in bundles.Targets is used for Asset bundle for compression output. 


'myAsset' => [
  'class' => 'yii\web\AssetBundle',
  'basePath' => '@webroot',
  'baseUrl' => '/',
  'js' => 'compress/my-compressed.js', 
  'css' => 'compress/my-compressed.css',
  'depends' => [
   'frontend\assets\main\MyAsset'
  ],
    ],
in targets you have to mention the depends assets which you have to use for the compression.

So, AllAsset should have the basePath setting equal to @webroot and the baseUrl setting equal to /. The problem is, at the point when frontend/web/config.php will be evaluated, there’ll be no @webroot alias defined, so we are left with paths shown in the following code:


'targets' => [
        'frontend\assets\main\MyAsset' => [
            'basePath' => '@webroot',
            'baseUrl' => '/',
            'js' => 'compiled-assets/all-{hash}.js',
            'css' => 'compiled-assets/all-{hash}.css',
        ],
    ], 

The {hash} token will be replaced by a unique hash for the corresponding file.

Now, run the command at last:

./yii asset frontend/web/config.php common/config/assets_compressed.php    

The first argument to the ./yii asset command is the path to the supplementary configuration file we worked so hard to forge until now. The second argument is the path to the file that will hold the resulting configuration snippet we’ll need to attach to our application. We decided to put it to the assets_compressed.php file near our other main configuration files.

The configuration snippet generated will hold the definitions of all asset bundles listed in bundles with js and css settings cleaned out. All these asset bundles will be made dependent on the newly-created asset bundle containing the compressed CSS and JavaScript files. We need to use the content of this configuration snippet as the value of the components.assetManager.bundles setting in the application configuration, so in our case, we just paste the following into the components section.


'assetManager' => [
            'bundles' => (require __DIR__ . '/assets_compressed.php')
        ],

Now you can see the action in your page view source . The js and css are minified.I hope this lession will help you to minified the css and js files in yii2.        


No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular