grunt学习

来源:互联网 发布:巨石监控分析软件 编辑:程序博客网 时间:2024/06/13 04:36

以前没有接触过前端自动化工具,grunt学起来费了不少精力。简单做下笔记。


假设你已经配置好了node环境,并安装了npm。


老项目中整合grunt :

第一步:在项目目录下执行命令npm init命令生成package.json文件:

npm init

① 利用npm install 命令 安装package.json中dependencies中模块:

此时,package.json中没有devDependencies 和 dependencies模块,我们可以手写devDependencies 和 dependencies模块,或者利用npm直接安装模块并写入devDependencies 和 dependencies模块:

如:利用npm安装grunt模块并写入devDenpencies:

npm install grunt --save-devnpm install time-grunt --save-dev
如:利用npm安装grunt模块并写入dependencies:

npm install grunt --savenpm install time-grunt --save
安装package.json中依赖模块:
npm install //安装package.json中的dependencies、devDenpencies中模块npm install –production  //安装package.json中的dependencies中模块。

devDependencies 和 dependencies区别:

devDependencies:测试环境中需要安装的模块,dependencies为生成环境需要的模块。

devDependencies只用于开发阶段完成集成测试等功能模块依赖。


第二步:新建并编写Gruntfile.js配置文件。

第三步:根据Gruntfile.js配置文件,开始执行grunt任务。

Gruntfile实例: http://www.gruntjs.net/sample-gruntfile


创建grunt新项目(利用yomen创建webapp新项目):

项目中用到了grunt、sass、bower,所以需要你的机器全局安装好 sass 、compass、grunt-cli、bower

1 安装yomen和generator-webapp

npm install yo -gnpm install generator-webapp -g

2 创建项目目录:

mkdir grunt-yo-webapp
3 利用yomen生成目录

yo webapp grunt-yo-webapp

项目生成在当前目录

利用yomen生成的项目中的GruntFile.js文件中已经配置好了任务,可以利用grunt 命令直接运行,

例如:

①执行grunt serve命令会自动在浏览器中打开app文件夹下面的index.html文件,并实时watch。

②执行grunt build命令会生成两个目录 ,.tmp和dist目录(项目生成的目录)。


Gruntfile.js配置任务:

参考:http://www.gruntjs.net/configuring-tasks


grunt配置任务学习:

以yeoman创建的webapp项目为例,学习下如何配置常用任务.

用yeoman创建好webapp任务后,在项目目录下会有一个package.json和Gruntfile.js文件。

package.json文件是npm的安装文件目录,里面使我们需要的所有插件(利用yeoman创建的项目会自动用npm安装package.json中的插件);

Gruntfile.js文件(实质是js文件,可执行任何有效的js代码)是grunt的配置文件,里面配置项目需要执行的任务。官方参考:http://www.gruntjs.net/configuring-tasks

package.json文件:


package.json文件中的grunt-contrib-requirejs和grunt-css-sprite是根据项目需要自行添加的。


先看一个常规的Gruntfile.js配置文件:

'use strict'; module.exports = function(grunt) {  grunt.initConfig({    jshint: {      //    },    watch: {      //    }  });  grunt.loadNpmTasks('grunt-contrib-jshint');  grunt.loadNpmTasks('grunt-contrib-watch');  grunt.registerTask('default', ['jshint']);};
第一部分是"wrapper" 函数,它包含了整个Grunt配置信息。
module.exports = function(grunt) {}

第二部分grunt.initConfig函数,我们的任务配置 (此配置主要是以任务名称命名的属性 ) 写在里面。

grunt.initConfig({  jshint: {},  watch: {}}

第三部分是加载所需要的Grunt插件

grunt.loadNpmTasks('grunt-contrib-jshint');grunt.loadNpmTasks('grunt-contrib-watch');

第四部分是设置一些task。

grunt.registerTask('default', ['jshint','watch']);

上面一行代码设置了名为default的任务,我们在控制台执行  grunt 或者 grunt default 则运行任务jshint、watch。

我们也可以用命令行 grunt jshint 来运行 jshint 任务,命令行 grunt watch 来运行 watch 任务。

grunt-contrib-requirejs插件配置:

grunt的项目中用到了requirejs,这里就用到了这个插件。实现requirejs模块的压缩整合。

Gruntfile.js关键代码(指定单个文件打包):

module.exports = function (grunt) {  grunt.initConfig({    requirejs: {      compile: {        "options": {          "baseUrl": "./",          "name": 'src/test02.js',          "paths": {            "$": "src/zepto",            "_": "src/underscore",            "B": "src/backbone",            "Test": "src/Test01"          },          "include": [            "$",            "_",            "B",            "Test"          ],          "out": "dest/libs.js"        }      }    }  });  grunt.loadNpmTasks('grunt-contrib-requirejs');}

Gruntfile.js关键代码(指定多个文件打包):

module.exports = function(grunt){    //grunt的配置我就不叨叨了 自己看官网就ok了    //我就介绍下grunt的依赖插件grunt-contrib-requirejs    //专门打包requeirjs项目的    grunt.initConfig({         //此处的requirejs的配置和requeirjs.config要区分开,那个是requeirjs项目加载配置        //这个是 grunt-contrib-requirejs打包配置        requirejs: {            build: {                options: {                    //此处是文件Gruntfile的相对位置                    appDir: './app',                    //设置默认路径 ./app/js                    baseUrl : 'js',                    //设置压缩后的路径 ./build                    dir: './build',                     //这里paths 是被打包文件所需要的依赖文件以及被打包的文件                    /*                        ./app/js/main.js下的代码                        requirejs([                                'angular',                                'jquery',                                'app'                            ], function (angular, $, app) {                                ......                        })                    */                    //需要三个angular jquery app                    //那么 其他的呢? 其他的模块会按照依赖关系也被打包进去                    //比如 app需要 ./app/js/controller/myCon.js grunt就自动把他打包进去了                    //我们只管 被打包的文件和此文件requirejs()函数加载的依赖 ....楼主好啰嗦                    paths: {                        'jquery': 'lib/jquery',                        'angular': 'lib/angular',                        'app' : 'app',                        'main' : 'main',                    },                     //requiejs.config里面配置了依赖关系和全局变量那为什么这还需要配置                    //因为 打包后代码的变量将被替换只有a b c d类似简单的变量了                    //那 angularjs自定义模块(比如myCon.js)就报undefined了                    //此处配置了,打包后就不报错了,grunt-contrib-requirejs给在中间转了一下                    shim: {                        angular : {                            deps : ['jquery'],                            exports : 'angular'                        },                        jquery : {                            exports : '$'                        }                    },                    //此处的modules就是要打包的文件(模块)                    //我们例子项目因为通过main.js就把整个项目模块 关联了起来                    //main ->angular+jquery+app ->myCon->mySer                    //所以我只打包main.js grunt就自动把其他依赖文件按依赖关系(顺序)打包进去                    modules: [{                        name: 'main'                    }]                }            }        },    });     grunt.loadNpmTasks('grunt-contrib-requirejs');    grunt.registerTask('merge', ['requirejs']);}

grunt-contrib-requirejs使用参考:

http://my.oschina.net/felumanman/blog/338595

http://www.cnblogs.com/yexiaochai/p/3602002.html

https://github.com/jrburke/r.js/blob/master/build/example.build.js



grunt-spritesmith:grunt 中css精灵处理插件

如果你是在window使用,除了安装grunt-spritesmith外还需要安装gm和phantomjs:

npm install grunt-spritesmithnpm install gmnpm install phantomjs

Gruntfile.js中相关配置:

grunt.initConfig({    ...    sprite:{      all: {        src: '<%= config.app %>/images/sprite/*.png',        dest: '<%= config.app %>/images/spritesheet.png',        destCss: '<%= config.app %>/styles/_icon.scss'      }    }});
假如sprite下面有两张图片:logo.png、logo2.png

main.scss 中需要定义:

@import "icon.scss";.div1{  @include sprite($logo);}.div2{  @include sprite($logo2);}
执行命令:grunt sprite 后,

生成拼合后的图片: spritesheet.png

生成_icon.scss 文件:

$logo-name: 'logo';$logo-x: 0px;$logo-y: 0px;$logo-offset-x: 0px;$logo-offset-y: 0px;$logo-width: 147px;$logo-height: 42px;$logo-total-width: 147px;$logo-total-height: 84px;$logo-image: '../images/spritesheet.png';$logo: (0px, 0px, 0px, 0px, 147px, 42px, 147px, 84px, '../images/spritesheet.png', 'logo', );$logo2-name: 'logo2';$logo2-x: 0px;$logo2-y: 42px;$logo2-offset-x: 0px;$logo2-offset-y: -42px;$logo2-width: 147px;$logo2-height: 42px;$logo2-total-width: 147px;$logo2-total-height: 84px;$logo2-image: '../images/spritesheet.png';$logo2: (0px, 42px, 0px, -42px, 147px, 42px, 147px, 84px, '../images/spritesheet.png', 'logo2', );$spritesheet-width: 147px;$spritesheet-height: 84px;$spritesheet-image: '../images/spritesheet.png';$spritesheet-sprites: ($logo, $logo2, );$spritesheet: (147px, 84px, '../images/spritesheet.png', $spritesheet-sprites, );@mixin sprite-width($sprite) {  width: nth($sprite, 5);}@mixin sprite-height($sprite) {  height: nth($sprite, 6);}@mixin sprite-position($sprite) {  $sprite-offset-x: nth($sprite, 3);  $sprite-offset-y: nth($sprite, 4);  background-position: $sprite-offset-x  $sprite-offset-y;}@mixin sprite-image($sprite) {  $sprite-image: nth($sprite, 9);  background-image: url(#{$sprite-image});}@mixin sprite($sprite) {  @include sprite-image($sprite);  @include sprite-position($sprite);  @include sprite-width($sprite);  @include sprite-height($sprite);}@mixin sprites($sprites) {  @each $sprite in $sprites {    $sprite-name: nth($sprite, 10);    .#{$sprite-name} {      @include sprite($sprite);    }  }}
执行命令:grunt sass 后,生成相应的main.css文件:

.div1 {  background-image: url(../images/spritesheet.png);  background-position: 0px 0px;  width: 147px;  height: 42px; }.div2 {  background-image: url(../images/spritesheet.png);  background-position: 0px -42px;  width: 147px;  height: 42px; }

至此完成简单完成。

问题:如何适应移动设备的视网膜屏幕?

spritesmith更多配置见:https://www.npmjs.com/package/grunt-spritesmith






遇到问题:

②应用MD5后,如何交付后台(不断的更改,每次要通知后台改)?



参考:http://javascript.ruanyifeng.com/tool/grunt.html

yeoman官网: http://yeoman.io/

0 0