Grunt教程-前端自动化

为何选择Grunt?

压缩、编译、单元测试、代码检查等 我们需要自动化,不必重复劳动,减小工作量。为何选择Grunt呢?好像是没有更好的选择了。

准备工作

安装node.js

Grunt基于Node.js,安装之前要先安装Node.js。

brew install node

更新npm

sudo npm install npm -g

安装 grunt-cli

安装 grunt-cli 并不等于安装了 Grunt 任务运行器
Grunt CLI 的任务是运行 Gruntfile 指定的 Grunt 版本。 这样就可以在一台电脑上同时安装多个版本的 Grunt。(没有懂,俺直接实战)

npm install -g grunt-cli

Grunt必备文件

创建文件必须创建文件夹,我建立了一个 test 的文件夹,一个标准的 grunt 项目中必须有两个文件。

package.json:用于保存项目元数据。
Gruntfile.js : 用于配置或定义任务、加载 Grunt 插件。

在test1文件夹中创建这两个文件吧。那么文件中写什么内容呢。我们首先来关注一下package.json写什么内容

{
  "name": "test",
  "version": "1.0.0"
}

运行

在项目的根目录下运行下面的命令

npm install

命令执行过程

npm WARN package.json test1@1.0.0 No description
npm WARN package.json test1@1.0.0 No repository field.
npm WARN package.json test1@1.0.0 No README data

提示说没有描述信息没有README之类的
在根目录添加一个 README.md 文件

添加内容

在 package.json 中添加下面内容之后

{
  "name": "test",
  "version": "1.0.0",
  "description": "测试的例子",
  "repository": {
    "type": "git",
    "url": "https://github.com/JSLite/JSLite.git"
  }
}

于是乎万事大吉了

安装 Grunt 插件

在此项目中安装 Grunt 插件

sudo npm install grunt --save-dev

package.json的文件内容发现多了 devDependencies 的信息
目录多了一个 node_modules 的文件夹

{
  "name": "test",
  "version": "1.0.0",
  "description": "测试的例子",
  "repository": {
    "type": "git",
    "url": "https://github.com/JSLite/JSLite.git"
  },
  "devDependencies": {
    "grunt": "^0.4.5"
  }
}

运行 npm install <module> --save-dev,不仅会安装指定的 模块,还会自动添加到 devDependencies 区域中,且包括 版本范围。

grunt-contrib-uglify

插件用途:压缩js,css文件
插件名称:grunt-contrib-uglify

安装

sudo npm install grunt-contrib-uglify --save-dev

安装成功之后 在package.json的文件内容中的 devDependencies 的信息又增加了

"devDependencies": {
  "grunt": "^0.4.5",
  "grunt-contrib-uglify": "^0.8.0"
}

使用方法

还记得我们上面说一个Grunt项目要两个必须的文件一个 package.json 和Gruntfile.js,注意大小写,Linux区分大小写的,创建 Gruntfile.js 并写入如下内容

// 包装函数
module.exports = function(grunt) {
 
  // 任务配置,所有插件的配置信息
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    
    // uglify插件的配置信息
    uglify: {
        options: {
          banner: '/*! This is uglify test - ' +
            '<%= grunt.template.today("yyyy-mm-dd") %> */',
          beautify: true,//是否压缩
          mangle: false, //不混淆变量名
          compress:true,//打开或关闭使用默认选项源压缩。 
          preserveComments: 'all', //不删除注释
        },
        app_task: {
          files: {
            'build/app.min.js': ['lib/index.js', 'lib/test.js']
          }
        },
        buildb:{//任务二:压缩b.js,输出压缩信息
            options: {
                report: "min"//输出压缩率,可选的值有 false(不输出信息),gzip
            },
            files: {
                'output/js/b.min.js': ['js/main/b.js']
            }
        },
        buildall: {//任务三:按原文件结构压缩js文件夹内所有JS文件
            files: [{
                expand:true,
                cwd:'js',//js目录下
                src:'**/*.js',//所有js文件
                dest: 'output/js'//输出到此目录下
            }]
        },
        release: {//任务四:合并压缩a.js和b.js
            files: {
                'output/js/index.min.js': ['js/a.js', 'js/main/b.js']
            }
        }
    }
  });
 
  // 告诉grunt我们将使用插件
  grunt.loadNpmTasks('grunt-contrib-uglify');
 
  // 告诉grunt当我们在终端中输入grunt时需要做些什么
  grunt.registerTask('default', ['uglify']);
 
};

分析

  • banner:在build/app.min.js 文件生成内容如日期什么的
  • files:将 lib 目录中的 js 压缩合并生成到 build 目录中生成 app.min.js

运行grunt

输入命令下面命令,好了,我的没有错误正常的。如果有错误,会有错误日志,自己分析哦。

grunt

grunt-contrib-watch

插件用途:监控文件变化并自动运行grunt的watch插件
插件名称:grunt-contrib-watch

安装

sudo npm install grunt-contrib-watch --save-dev

使用

修改 Gruntfile.js

initConfig 中添加了

// watch插件的配置信息
watch: {
    another: {
        files: ['lib/*.js'],
        tasks: ['uglify'],
        options: {
            // Start another live reload server on port 1337
            livereload: 1337
        }
    }
}

增加了一行

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

数组中添加了watch

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

添加了watch后,完整的 Gruntfile.js

// 包装函数
module.exports = function(grunt) {
 
  // 任务配置,所有插件的配置信息
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    
    // uglify插件的配置信息
    uglify: {
        options: {
          banner: '/*! This is uglify test - ' +
            '<%= grunt.template.today("yyyy-mm-dd") %> */'
        },
        app_task: {
          files: {
            'build/app.min.js': ['lib/index.js', 'lib/test.js']
          }
        }
    },


    // watch插件的配置信息
    watch: {
        another: {
            files: ['lib/*.js'],
            tasks: ['uglify'],
            options: {
                // Start another live reload server on port 1337
                livereload: 1337
            }
        }
    }


  });
 
  // 告诉grunt我们将使用插件
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
 
  // 告诉grunt当我们在终端中输入grunt时需要做些什么
  grunt.registerTask('default', ['uglify','watch']);
 
};

grunt-contrib-watch

安装 stylus

sudo npm install grunt-contrib-watch --save-dev

修改 Gruntfile.js

initConfig 中添加了

stylus:{
    build: {
        options: {
            linenos: false,
            compress: false,
            banner: '\/** \n * <%= pkg.name %> - <%= pkg.description %>\n * version <%= pkg.version %> \n * author <%= pkg.author %> \n * date <%= grunt.template.today() %> \n**/\n'
        },
        files: [{
            'css/historyDetail.css': 'styl/historyDetail.styl'
        }]
    }
},

下面添加

grunt.loadNpmTasks('grunt-contrib-stylus');

paths 将自动使用@import来引入一些Stylus文件,比如一些Mixin集合,放在一个Stylus文件中进行维护,写在paths中后,就可以在每个Stylus文件中调用它们。define 可以定义一些全局变量,然后在Stylus中使用,但我不喜欢使用这个配置,而是更喜欢把全局变量放在一个单独的Stylus文件中,然后将这个文件加入paths的数组中。一句话,把所有不会直接产出CSS的Stylus代码分成若干个Stylus文件,然后全部添加到paths中,这样在所有Stylus文件中都可以随时调用了,但要注意这些Stylus文件的调用关系和使用先后顺序。

compress 及 linenos 是两个Boolean值,用来控制是否压缩处理后的CSS代码以及是否在CSS代码中保留注释。

banner 是一个字符串,会被放置在CSS文件的最前面,一般我用来写注释,比如

banner: '\/** \n * <%= pkg.name %> - <%= pkg.description %>\n * version <%= pkg.version %> \n * author <%= pkg.author %> \n * date <%= grunt.template.today() %> \n**/\n'

firebug 将控制是否使用一个FirebugStylus插件FireStylus for Firebug,可以在Firefox中调试Stylus。

use 可以引入一些Stylus的其他grunt插件。

常用模块设置

grunt-contrib-clean:删除文件。npm>>
grunt-contrib-compass:使用compass编译sass文件。npm>>
grunt-contrib-concat:合并文件。npm>>
grunt-contrib-copy:复制文件。npm>>
grunt-contrib-cssmin:压缩以及合并CSS文件。npm>>
grunt-contrib-imagemin:图像压缩模块。npm>>
grunt-contrib-jshint:检查JavaScript语法。npm>>
grunt-contrib-uglify:压缩以及合并JavaScript文件。npm>>
grunt-contrib-watch:监视文件变动,做出相应动作。npm>>
grunt-contrib-stylus:stylus编写styl输出css npm>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值