yii2笔记:asset压缩js,css文件

官网文档

http://www.yiiframework.com/doc-2.0/guide-structure-assets.html

 

yii目录下运行

asset/template assets.php

生成assets.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 compiler.jar --js {from} --js_output_file {to}',
    'jsCompressor' => 'java -jar yuicompressor.jar --type js {from} -o {to}',
    // Adjust command/callback for CSS files compressing:
    'cssCompressor' => 'java -jar yuicompressor.jar --type css {from} -o {to}',
    // The list of asset bundles to compress:
    'bundles' => [
        'app\assets\AppAsset',
        'yii\web\YiiAsset',
        'yii\web\JqueryAsset',
    ],
    // Asset bundle for compression output:
    'targets' => [
        'all' => [
            'class' => 'yii\web\AssetBundle',
            'basePath' => '@webroot/assets',
            'baseUrl' => '@web/assets',
            'js' => 'js/all-{hash}.js',
            'css' => 'css/all-{hash}.css',
        ],
    ],
    // Asset manager configuration:
    'assetManager' => [
        'basePath' => '@webroot/assets',
        'baseUrl' => '@web/assets',
    ],
];

  

这里css和js全部用yuicompressor了

然后在web/assets下创建js,css文件夹,并设置权限777

 

安装java命令行,ubuntu下

sudo apt-get install default-jre

 

下载yuicompressor.jar:

https://github.com/yui/yuicompressor/releases

放到yii根目录下

 

运行

./yii asset assets.php config/assets-dev.php

在config下会生成assets-dev.php文件

 

在config/web.php的component配置中添加

        'assetManager' => [
            'bundles' => require(__DIR__ . '/assets-' . YII_ENV . '.php'),
        ],

 

F5刷新页面就可以看到使用了压缩后的css和js了

如果要取消,注释掉web.php中对应代码即可

posted @ 2016-11-24 14:47 zergling9999 阅读(...) 评论(...) 编辑 收藏