JavaScript 項目構建工具 Grunt 實踐:安裝和創建項目框架

   Grunt 是一個基於任務的 JavaScript 項目命令行構建工具,運行於 Node.js 平臺。Grunt 能夠從模板快速創建項目,合併、壓縮和校驗 CSS & JS 文件,運行單元測試以及啓動靜態服務器。

 

  

 

安裝 Grunt

  推薦 Windows 用戶使用 Git Shell 來進行命令行操作。安裝 Windows 桌面版 GitHub 的時候會自動安裝 Git Shell。

  GitHub for Windows 下載地址:http://windows.github.com

  Grunt 運行於 Node.js 環境,這裏假設你已經安裝了 Node.js 和 NPM。


npm install grunt

  爲了便於操作,可以使用參數 -g 配置爲全局安裝:


npm install -g grunt

  

創建項目框架

  安裝好 Grunt 後就可以開始創建項目了,Grunt 內置下面四種基本的項目模板:

  gruntfile,創建命令:


grunt init:gruntfile

  commonjs,創建命令:


grunt init:commonjs

  jquery,創建命令:


grunt init:jquery

  node,創建命令:


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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章