JavaScript 项目构建工具 Grunt 实践:安装和建立项目框架

   Grunt 是一个基于任务的 JavaScript 项目命令行构建工具,运行于 Node.js 平台。Grunt 可以从模板快速建立项目,合并、压缩和校验 CSS & JS 文件,运行单元测试以及启动静态服务器。javascript

 

  

 

安装 Grunt

  推荐 Windows 用户使用 Git Shell 来进行命令行操做。安装 Windows 桌面版 GitHub 的时候会自动安装 Git Shell。css

  GitHub for Windows 下载地址:http://windows.github.comhtml

  Grunt 运行于 Node.js 环境,这里假设你已经安装了 Node.js 和 NPM。前端

npm install grunt

  为了便于操做,能够使用参数 -g 配置为全局安装:java

npm install -g grunt

  

建立项目框架

  安装好 Grunt 后就能够开始建立项目了,Grunt 内置下面四种基本的项目模板:node

  gruntfile,建立命令:jquery

grunt init:gruntfile

  commonjs,建立命令:css3

grunt init:commonjs

  jquery,建立命令:git

grunt init:jquery

  node,建立命令:github

grunt init:node

  咱们今天建立的是 jQuery 项目,编写一个 jQuery 插件示例。如今 GitHub 建立好示例仓库 GruntDemo,而后使用桌面版工具克隆到本地,在 Git Shell 中进入仓库目录,再输入 grunt init:jquery 命令进行建立,若是当前位置已存在项目,可能会有以下提示:

  

  若是须要覆盖,这个时候须要使用 --forece 参数:

grunt init:jquery --force

  建立项目时,须要填写一些项目的基本信息,例如项目名称、描述、仓库地址、做者信息(后面几项有默认内容)等,如图示:

  

  OK,到这里项目就建立成功了!下面是项目的目录结构:

  

  而且 README.md 文件的内容和格式也生成好了:

  

  而后就能够编写插件代码了。Grunt 提供的 jQuery 插件代码框架以下:

/*
 * GruntDemo
 * https://github.com/bluesky/grunt-demo
 *
 * Copyright (c) 2013 BlueSky
 * Licensed under the MIT license.
 */

(function($) {

  // Collection method.
  $.fn.awesome = function() {
    return this.each(function() {
      $(this).html('awesome');
    });
  };

  // Static method.
  $.awesome = function() {
    return 'awesome';
  };

  // Custom selector.
  $.expr[':'].awesome = function(elem) {
    return elem.textContent.indexOf('awesome') >= 0;
  };

}(jQuery));

  同时还生成了相应的 Qunit 测试代码和页面:

/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/
(function($) {

  module('jQuery#awesome', {
    setup: function() {
      this.elems = $('#qunit-fixture').children();
    }
  });

  test('is chainable', 1, function() {
    // Not a bad test to run on collection methods.
    strictEqual(this.elems.awesome(), this.elems, 'should be chaninable');
  });

  test('is awesome', 1, function() {
    strictEqual(this.elems.awesome().text(), 'awesomeawesomeawesome', 'should be thoroughly awesome');
  });

  module('jQuery.awesome');

  test('is awesome', 1, function() {
    strictEqual($.awesome(), 'awesome', 'should be thoroughly awesome');
  });

  module(':awesome selector', {
    setup: function() {
      this.elems = $('#qunit-fixture').children();
    }
  });

  test('is awesome', 1, function() {
    // Use deepEqual & .get() when comparing jQuery objects.
    deepEqual(this.elems.filter(':awesome').get(), this.elems.last().get(), 'knows awesome when it sees it');
  });

}(jQuery));

  

  下篇预告:《JavaScript 项目构建工具 Grunt 实践:任务和指令》,敬请期待……

您可能感兴趣的相关文章

 

本文连接:JavaScript 项目构建工具 Grunt 实践:简介和安装

编译来源:梦想天空 ◆ 关注前端开发技术 ◆ 分享网页设计资源

hide

相关文章
相关标签/搜索