Yii2 Asset 压缩配置流程
参考官方文档说明
访问 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
将下载的 jar 包放置于 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 中对应的代码段
此外需注意 Yii2 控制器、方法命名规范及访问路由规则
当模块、控制器或动作名称采用骆驼式命名法时,URL 路由中每个大写字母单词间需以连字符“-”连接
例如 DateTimeController::actionFastForward 对应的路由应为 date-time/fast-forward
具体示例如:http://dfms.com/backend/web/api-test/test-upload
其中 api-test 代表控制器名称
test-upload 代表方法名称
以上介绍了 Yii2 中使用 Asset 压缩 JS 和 CSS 的方法及相关路由规范,希望能对大家有所帮助。如有任何疑问欢迎留言,小编会及时回复。感谢大家对本站的支持!