1. 程式人生 > >【grunt整合版】30分鐘學會使用grunt打包前端程式碼

【grunt整合版】30分鐘學會使用grunt打包前端程式碼

grunt

是一套前端自動化工具,一個基於nodeJs的命令列工具,一般用於:
① 壓縮檔案
② 合併檔案
③ 簡單語法檢查

對於其他用法,我還不太清楚,我們這裡簡單介紹下grunt的壓縮、合併檔案,初學,有誤請包涵

準備階段

1、nodeJs環境

因為grunt是基於nodeJs的,所以首先各位需要安裝nodeJS環境,這塊我們便不管了
http://www.cnblogs.com/yexiaochai/p/3527418.html

2、安裝grunt

有了nodeJs環境後,我們便可以開始搞grunt了,因為我們可能在任何目錄下執行打包程式,所以我們需要安裝CLI
官方推薦在全域性安裝CLI(grunt的命令列介面)

npm install -g grunt-cli

這條命令將會把grunt命令植入系統路徑,這樣就能在任意目錄執行他,原因是

每次執行grunt時,它都會使用node的require查詢本地是否安裝grunt,如果找到CLI便載入這個本地grunt庫
然後應用我們專案中的GruntFile配置,並執行任務
PS:這段先不要管,安裝完了往下看

例項學習:打包zepto

一些東西說多了都是淚,直接先上例項吧,例項結束後再說其它的
首先在D盤新建一個專案(資料夾就好)
在裡面新增兩個檔案(不要問為什麼,搞進去先)

① package.json

{
  "name": "demo",
  
"file": "zepto", "version": "0.1.0", "description": "demo", "license": "MIT", "devDependencies": { "grunt": "~0.4.1", "grunt-contrib-jshint": "~0.6.3", "grunt-contrib-uglify": "~0.2.1", "grunt-contrib-requirejs": "~0.4.1", "grunt-contrib-copy": "~0.4.1", "grunt-contrib-clean": "~0.5.0",
"grunt-strip": "~0.2.1" }, "dependencies": { "express": "3.x" } }

② Gruntfile.js

完了我們需要在grunt目錄下執行 npm install將相關的檔案下載下來:

$ cd d:
$ cd grunt

然後我們的目錄就會多一點東西:

多了很多東西,先別管事幹什麼的,我們後面都會用到,這個時候在目錄下新建src資料夾,並且搞一個zepto進去

然後在Gruntfile中新增以下程式碼(先別管,增加再說)

module.exports = function (grunt) {
  // 專案配置
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      options: {
        banner: '/*! <%= pkg.file %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: 'src/<%=pkg.file %>.js',
        dest: 'dest/<%= pkg.file %>.min.js'
      }
    }
  });
  // 載入提供"uglify"任務的外掛
  grunt.loadNpmTasks('grunt-contrib-uglify');
  // 預設任務
  grunt.registerTask('default', ['uglify']);
}

然後執行 grunt命令後

grunt

嗯嗯,多了一個檔案,並且是壓縮的,不差!!!第一步結束

認識Gruntdile與package.json

不出意外,每一個gurnt都會需要這兩個檔案,並且很可能就只有這兩個檔案(複雜的情況有所不同)

package.json

這個檔案用來儲存npm模組的依賴項(比如我們的打包若是依賴requireJS的外掛,這裡就需要配置)
然後,我們會在裡面配置一些不一樣的資訊,比如我們上面的file,這些資料都會放到package中
對於package的靈活配置,我們會在後面提到

Gruntfile

這個檔案尤其關鍵,他一般幹兩件事情:
① 讀取package資訊
② 外掛載入、註冊任務,執行任務(grunt對外的介面全部寫在這裡面)

Gruntfile一般由四個部分組成
① 包裝函式
這個包裝函式沒什麼東西,意思就是我們所有的程式碼必須放到這個函式裡面

module.exports = function (grunt) {
//你的程式碼
}

這個不用知道為什麼,直接將程式碼放入即可

② 專案/任務配置
我們在Gruntfile一般第一個用到的就是initConfig方法配置依賴資訊

pkg: grunt.file.readJSON('package.json')

這裡的 grunt.file.readJSON就會將我們的配置檔案讀出,並且轉換為json物件

然後我們在後面的地方就可以採用pkg.XXX的方式訪問其中的資料了
值得注意的是這裡使用的是underscore模板引擎,所以你在這裡可以寫很多東西

uglify是一個外掛的,我們在package依賴項進行了配置,這個時候我們為系統配置了一個任務
uglify(壓縮),他會幹這幾個事情:

① 在src中找到zepto進行壓縮(具體名字在package中找到)
② 找到dest目錄,沒有就新建,然後將壓縮檔案搞進去
③ 在上面加幾個描述語言

這個任務配置其實就是一個方法介面呼叫,按照規範來就好,暫時不予關注,內幕後期來
這裡只是定義了相關引數,但是並未載入實際函式,所以後面馬上就有一句:

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

用於載入相關外掛

最後註冊一個自定義任務(其實也是預設任務),所以我們下面的命令列是等效的:

grunt == grunt uglify

至此,我們就簡單解析了一番grunt的整個操作,下面來合併檔案的例子

合併檔案

合併檔案依賴於grunt-contrib-concat外掛,所以我們的package依賴項要新增一項

"devDependencies": {
  "grunt": "~0.4.1",
  "grunt-contrib-jshint": "~0.6.3",
  "grunt-contrib-concat": "~0.3.0",
  "grunt-contrib-uglify": "~0.2.1",
  "grunt-contrib-requirejs": "~0.4.1",
  "grunt-contrib-copy": "~0.4.1",
  "grunt-contrib-clean": "~0.5.0",
  "grunt-strip": "~0.2.1"
},

然後再將程式碼寫成這個樣子

module.exports = function (grunt) {
  // 專案配置
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';'
      },
      dist: {
        src: ['src/zepto.js', 'src/underscore.js', 'src/backbone.js'],
        dest: 'dest/libs.js'
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-concat');
  // 預設任務
  grunt.registerTask('default', ['concat']);
}

執行後,神奇的一幕發生了:

三個檔案被壓縮成了一個,但是沒有壓縮,所以,我們這裡再加一步操作,將之壓縮後再合併

module.exports = function (grunt) {
  // 專案配置
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';'
      },
      dist: {
        src: ['src/zepto.js', 'src/underscore.js', 'src/backbone.js'],
        dest: 'dest/libs.js'
      }
    },
    uglify: {
      build: {
        src: 'dest/libs.js',
        dest: 'dest/libs.min.js'
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  // 預設任務
  grunt.registerTask('default', ['concat', 'uglify']);
}

我這裡的做法是先合併形成一個libs,然後再將libs壓縮成libs.min.js

所以我們這裡換個做法,先壓縮再合併,其實unglify已經幹了這些事情了

module.exports = function (grunt) {
  // 專案配置
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      "my_target": {
        "files": {
          'dest/libs.min.js': ['src/zepto.js', 'src/underscore.js', 'src/backbone.js']
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-uglify');
  // 預設任務
  grunt.registerTask('default', ['uglify']);
}

所以,我們就暫時不去關注concat了

最後,今天時間不早了,我們最後研究下grunt配合require於是便結束今天的學習吧

合併requireJS管理的檔案

有了前面基礎後,我們來幹一件平時很頭疼的事情,便是將require管理的所有js檔案給壓縮了合併為一個檔案
首先我們建立一個簡單的程式,裡面使用了zepto、backbone、underscore(事實上我並未使用什麼)

在main.js中新增程式碼:

require.config({
 baseUrl: '',
 shim: {
  $: {
      exports: 'zepto'
  },
  _: {
   exports: '_'
  },
  B: {
   deps: [
    '_',
    '$'
     ],
   exports: 'Backbone'
  }
 },
 paths: {
  '$': 'src/zepto',
  '_': 'src/underscore',
  'B': 'src/backbone'
 }
});
requirejs(['B'], function (b) {
});

這樣的話執行會自動載入幾個檔案,我們現在希望將之合併為一個libs.js該怎麼幹呢???

我們這裡使用自定義任務方法來做,因為我們好像沒有介紹他

要使用requireJS相關需要外掛 

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

因為我們以後可能存在配置檔案存在各個專案檔案的情況,所以我們這裡將requireJs相關的配置放入gruntCfg.json中

這樣我們的package.json就沒有什麼實際意義了:

{
  "name": "demo",
  "version": "0.1.0",
  "description": "demo",
  "license": "MIT",
  "devDependencies": {
 "grunt": "~0.4.1",
 "grunt-contrib-jshint": "~0.6.3",
 "grunt-contrib-concat": "~0.3.0",
 "grunt-contrib-uglify": "~0.2.1",
 "grunt-contrib-requirejs": "~0.4.1",
 "grunt-contrib-copy": "~0.4.1",
 "grunt-contrib-clean": "~0.5.0",
 "grunt-strip": "~0.2.1"
 
  },
  "dependencies": {
    "express": "3.x"
  }
}

我們這裡設定的require相關的grunt配置檔案如下(gruntCfg.json):

{
  "requirejs": {
    "main": {
      "options": {
        "baseUrl": "",
        "paths": {
          "$": "src/zepto",
          "_": "src/underscore",
          "B": "src/backbone",
          "Test": "src/Test"
        },
        "web": {
          "include": [
            "$",
            "_",
            "B",
            "Test"
          ],
          "out": "dest/libs.js"
        }
      }
    }
  }
}

這裡我們要打包這些檔案搞到dest的libs.js檔案中,這個檔案照做就行,最後核心程式碼如下:

module.exports = function (grunt) {
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  //為了介紹自定義任務搞了一個這個
  grunt.registerTask('build', 'require demo', function () {
    //任務列表
    var tasks = ['requirejs'];
    //原始碼檔案
    var srcDir = 'src';
    //目標檔案
    var destDir = 'dest';
    //設定引數
    grunt.config.set('config', {
      srcDir: srcDir,
      destDir: destDir
    });
    //設定requireJs的資訊
    var taskCfg = grunt.file.readJSON('gruntCfg.json');
    var options = taskCfg.requirejs.main.options,
        platformCfg = options.web,
        includes = platformCfg.include,
        paths = options.paths;
    var pos = -1;
    var requireTask = taskCfg.requirejs;
    options.path = paths;
    options.out = platformCfg.out;
    options.include = includes;
    //執行任務
    grunt.task.run(tasks);
    grunt.config.set("requirejs", requireTask);
  });
}

搞完了執行就好:grunt build

grunt build

最後發現葉小釵三字,我就放心了,安全!!!!!!

配置任務/grunt.initConfig

前面我們簡單的介紹了grunt相關的知識,這裡我們這裡還需要再熟悉下Gruntfile相關的知識點,比如說配置任務

grunt的任務配置都是在Gruntfile中的grunt.initConfig方法中指定的,這個配置主要都是一些命名性屬性
比如我們上次用到的合併以及壓縮的任務配置:

grunt.initConfig({
    concat: {
        //這裡是concat任務的配置資訊
    },
    uglify: {
        //這裡是uglify任務的配置資訊
    },
    //任意非任務特定屬性
    my_property: 'whatever',
    my_src_file: ['foo/*.js', 'bar/*.js']
});

其中的my_property完全可能讀取外部json配置檔案,然後在上面任務配置中便可以,比如我們要壓縮的檔案為準或者最後要放到哪裡,便可以在此配置

我們使用grunt的時候,主要工作就是配置任務或者建立任務,實際上就是做一個事件註冊,然後由我們觸發之,所以grunt的核心還是事件註冊
每次執行grunt時,我們可以指定執行一個或者多個任務,通過任務決定要做什麼,比如我們同時要壓縮和合並還要做程式碼檢查

grunt.registerTask('default', ['jshint','qunit','concat','uglify']);

當執行一個基本任務時,grunt並不會查詢配置和檢查執行環境,他僅僅執行指定的任務函式,可以傳遞冒號分割引數,比如:

grunt.registerTask('foo', 'A sample task that logs stuff.', function (arg1, arg2) {
  if (arguments.length === 0) {
    grunt.log.writeln(this.name + ", no args");
  } else {
    grunt.log.writeln(this.name + ", " + arg1 + " " + arg2);
  }
});

執行結果如下:

$ grunt foo:testing:123
Running "foo:testing:123" (foo) task
foo, testing 123

$ grunt foo:testing
Running "foo:testing" (foo) task
foo, testing undefined

$ grunt foo
Running "foo" task
foo, no args

這裡有個多工的情況,就是一個任務裡面實際上第一了多個東東,這個時候就有所不同

grunt.initConfig({
    log: {
        demo01: [1,2,3],
        demo02: 'hello world',
        demo03: false
    }
});
grunt.registerTask('log','log stuff.', function(){
    grunt.log.writeln(this.target + ': ' + this.data);
});

如果我們執行,執行情況如下:

???????

更多時候,我們實際場景中都會需要自定義任務,而在我們任務內部使用 grunt.task.run({}) 執行任務
這塊的知識點,我們後面以實際例子說明

grunt外掛

學習grunt主要就是學習grunt的外掛使用,所以我們今天先來學習常用的幾個外掛

grunt-contrib-unglify

我們仍然以簡單例子學習

module.exports = function (grunt) {
  grunt.initConfig({
    uglify: {
      my_target: {
        files: {
          'dest/libs.min.js': ['src/zepto.js', 'src/underscoce.js']
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-uglify');
}

這樣會將src裡面的zepto等檔案打包值dest的lib.min.js中

壓縮一個資料夾的所有檔案

然後這段程式碼非常有意思,他會將一個檔案目錄裡面的所有js檔案打包到另一個資料夾

module.exports = function (grunt) {
  grunt.initConfig({
    uglify: {
      my_target: {
        files: [{
          expand: true,
          cwd: 'src',
          src: '**/*.js',
          dest: 'dest'
        }]
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-uglify');
}

若是你希望給你檔案的頭部加一段註釋性語言配置banner資訊即可

grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  uglify: {
    options: {
      banner: '/*! 註釋資訊 */'
    },
    my_target: {
      files: {
        'dest/output.min.js': ['src/input.js']
      }
    }
  }
});

grunt-contrib-concat

該外掛主要用於程式碼合併,將多個檔案合併為一個,我們前面的uglify也提供了一定合併的功能
在可選屬性中我們可以設定以下屬性:
① separator 用於分割各個檔案的文字,
② banner 前面說到的檔案頭註釋資訊,只會出現一次
③ footer 檔案尾資訊,只會出現一次
④ stripBanners去掉原始碼註釋資訊(只會清楚/**/這種註釋)

一個簡單的例子:

module.exports = function (grunt) {
  grunt.initConfig({
  concat: {
    options: {
      separator: '/*分割*/',
      banner: '/*測試*/',
      footer: '/*footer*/'
     
    },
    dist: {
      src: ['src/zepto.js', 'src/underscore.js', 'src/backbone.js'],
      dest: 'dist/built.js',
    }
  }
});
  grunt.loadNpmTasks('grunt-contrib-concat');
}

合併三個檔案為一個,這種在我們原始碼除錯時候很有意義

構建兩個資料夾

有時候我們可能需要將合併的程式碼放到不同的檔案,這個時候可以這樣幹

module.exports = function (grunt) {
  grunt.initConfig({
    concat: {
      basic: {
        src: ['src/zepto.js'],
        dest: 'dest/basic.js'
      },
      extras: {
        src: ['src/underscore.js', 'src/backbone.js'],
        dest: 'dest/with_extras.js'
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-concat');
}

這種功能還有這樣的寫法:

module.exports = function (grunt) {
  grunt.initConfig({
    concat: {
      basic_and_extras: {
        files: {
          'dist/basic.js': ['src/test.js', 'src/zepto.js'],
          'dist/with_extras.js': ['src/underscore.js', 'src/backbone.js']
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-concat');
}

第二種寫法便於使用配置檔案,具體各位選取吧,至於讀取配置檔案的東西我們這裡就先不關注了

grunt-contrib-jshint

該外掛用於檢測檔案中的js語法問題,比如我test.js是這樣寫的:

alert('我是葉小釵')
module.exports = function (grunt) {
  grunt.initConfig({
    jshint: { 
      all: ['src/test.js']
    }
  });
  grunt.loadNpmTasks('grunt-contrib-jshint');
}

執行結果是:

$ grunt jshint
Running "jshint:all" (jshint) task
Linting src/test.js ...ERROR
[L1:C15] W033: Missing semicolon.
alert('我是葉小釵')

說我缺少一個分號,好像確實缺少.....如果在裡面寫明顯的BUG的話會報錯
多數時候,我們認為沒有分號無傷大雅,所以,我們檔案會忽略這個錯誤:

jshint: {
  options: {
    '-W033': true
  },
  all: ['src/test.js']
}

這裡有一個稍微複雜的應用,就是我們合併之前做一次檢查,合併之後再做一次檢查,我們可以這樣寫

module.exports = function (grunt) {
  grunt.initConfig({
    concat: {
      dist: {
        src: ['src/test01.js', 'src/test02.js'],
        dest: 'dist/output.js'
      }
    },
    jshint: {
      options: {
        '-W033': true 
      },
      pre: ['src/test01.js', 'src/test02.js'],
      after: ['dist/output.js']
    }
  });
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-jshint');
}
$ grunt jshint:pre concat jshint:after
Running "jshint:pre" (jshint) task
>> 2 files lint free.
Running "concat:dist" (concat) task
File "dist/output.js" created.
Running "jshint:after" (jshint) task
>> 1 file lint free.

這裡連續運行了三個任務,先做檢查再合併,然後做檢測,我這裡寫了兩個簡單的檔案,如果將jquery搞進去的話,好像還出了不少BUG......
所以真的要用它還要自定一些規範,我們這裡暫時到這裡,先進入下一個外掛學習

grunt-contrib-requirejs

我們的grunt打包程式極有可能與requirejs一起使用,但是幾個外掛學習下來又屬requireJs的使用最為麻煩,因為網上資源很少,搞到這一段耗掉了我很多精力

這個時候你就會感嘆,英語好不一定程式設計好,英語差想成為高手還是不簡單啊!!!

requirejs: {
  compile: {
    options: {
      baseUrl: "path/to/base",
      mainConfigFile: "path/to/config.js",
      name: "path/to/almond", // assumes a production build using almond
      out: "path/to/optimized.js"
    }
  }
}

官方的例子首先就是這幾個屬性:

baseUrl 代表所有的js檔案都會相對於這個目錄

mainConfigFile 配置檔案目錄

name ???

out 輸出檔案

一些引數我們不太瞭解,這個時候就只能以例子破之了

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

這樣配置後,會將include裡面的檔案打包為out對應的檔案,paths的本身意義不大,就是用於配置include裡面的指向

這個時候我們來加個name看看有神馬作用:

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');
}

這樣的話,會將name對應檔案壓縮到壓縮檔案的最前面,但是具體是幹什麼的,還是不太清楚,其英文註釋說是單個檔案或者其依賴項優化,不知道優化什麼啊。。。囧!!!

requireJS基本的用法就是這樣了,其詳細資訊,我們過段時間再來看看,下面說一下requireJS的其它用法

我們這裡將requireJS的配置資訊放在外面,而Gruntfile採用自定義任務的方式完成上面的功能

配置檔案/cfg.json

{requirejs: {
  "options": {
    "baseUrl": "./",
    "paths": {
      "$": "src/zepto",
      "_": "src/underscore",
      "B": "src/backbone",
      "Test": "src/Test01"
    },
    "include": [
      "$",
      "_",
      "B",
      "Test"
    ],
    "out": "dest/libs.js"
  }
}}

然後,這裡我們便不是有initConfig的做法了,直接使用自定義任務

module.exports = function (grunt) {

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

  grunt.registerTask('build', 'require demo', function () {

    //第一步,讀取配置資訊
    var cfg = grunt.file.readJSON('cfg.json');
    cfg = cfg.requirejs;
    grunt.config.set('requirejs', { test: cfg });

    //第二步,設定引數
    grunt.log.debug('引數:' + JSON.stringify(grunt.config()));

    //第三步跑任務
    grunt.task.run(['requirejs']);
    
  });

}
$ grunt build --debug
Running "build" task
[D] Task source: d:\grunt\Gruntfile.js
[D] 引數:{"requirejs":{"test":{"options":{"baseUrl":"./","paths":{"$":"src/zept
o","_":"src/underscore","B":"src/backbone","Test":"src/Test01"},"include":["$","
_","B","Test"],"out":"dest/libs.js"}}}}

Running "requirejs:test" (requirejs) task
[D] Task source: d:\grunt\node_modules\grunt-contrib-requirejs\tasks\requirejs.j
s
>> Tracing dependencies for: d:/grunt/dest/libs.js
>> Uglifying file: d:/grunt/dest/libs.js
>> d:/grunt/dest/libs.js
>> ----------------
>> d:/grunt/src/zepto.js
>> d:/grunt/src/underscore.js
>> d:/grunt/src/backbone.js
>> d:/grunt/src/Test01.js

效果還是有的,最後我們介紹下requireJS打包模板檔案

require與模板檔案

我們知道,模板檔案一般都是html,比如我們這裡的demo01.html,對於這個檔案我們應該怎麼打包呢?其實很簡單......

需要幹兩件事情:

① 引入require.text

② 加入模板檔案

{
  "requirejs": {
    "options": {
      "baseUrl": "./",
      "paths": {
        "$": "src/zepto",
        "_": "src/underscore",
        "B": "src/backbone",
        "test": "src/test01",
        "text": "src/require.text"

      },
      "include": [
        "$",
        "_",
        "B",
        "test",
        "text!src/demo01.html"
      ],
      "out": "dest/libs.js"
    }
  }
}

於是,我們便成功將模板打入了

$ grunt build --debug
Running "build" task
[D] Task source: d:\grunt\Gruntfile.js
[D] 引數:{"requirejs":{"test":{"options":{"baseUrl":"./","paths":{"$":"src/zept
o","_":"src/underscore","B":"src/backbone","test":"src/test01","text":"src/requi
re.text"},"include":["$","_","B","test","text!src/demo01.html"],"out":"dest/libs
.js"}}}}

Running "requirejs:test" (requirejs) task
[D] Task source: d:\grunt\node_modules\grunt-contrib-requirejs\tasks\requirejs.j
s
>> Tracing dependencies for: d:/grunt/dest/libs.js
>> Uglifying file: d:/grunt/dest/libs.js
>> d:/grunt/dest/libs.js
>> ----------------
>> d:/grunt/src/zepto.js
>> d:/grunt/src/underscore.js
>> d:/grunt/src/backbone.js
>> d:/grunt/src/test01.js
>> d:/grunt/src/require.text.js
>> text!src/demo01.html

在檔案中我們引用方式是:

"text!src/demo01.html" => '具體檔案'

過濾關鍵字

 1 module.exports = function (grunt) {
 2   grunt.initConfig({
 3     requirejs: {
 4       compile: {
 5         "options": {
 6           optimize: 'uglify2',
 7           uglify2: {
 8             mangle: {
 9               except: ["$super"]
10             }
11           },
12           "baseUrl": "./",
13           "paths": {
14             "UIAbstractView": "ui_beta/ui.abstract.view",
15             "UILayer": "ui_beta/ui.layer"
16           },
17           "include": [
18             "UIAbstractView"
19           ],
20           "out": "dest/libs.js"
21         }
22       }
23     }
24   });
25   grunt.loadNpmTasks('grunt-contrib-requirejs');
26   grunt.registerTask('default', ['requirejs']);

打包樣式檔案

樣式檔案的打包方式與js不太一樣,這裡我們下載css-min外掛,並且在package.json中新增依賴項

{
  "name": "demo",
  "version":         "0.1.0",
  "description":     "demo",
  "license":         "MIT",
  "devDependencies": {
    "grunt":                   "~0.4.1",
    "grunt-contrib-jshint":    "~0.6.3",
    "grunt-contrib-concat":    "~0.3.0",
    "grunt-contrib-uglify":    "~0.2.1",
    "grunt-contrib-requirejs": "~0.4.1",
    "grunt-contrib-copy":      "~0.4.1",
    "grunt-contrib-clean":     "~0.5.0",
    "grunt-strip":             "~0.2.1",
    "grunt-contrib-watch": "~0.6.0",
    "grunt-contrib-cssmin": "~0.5.0"
  },
  "dependencies":    {
    "express": "3.x"
  }
}
module.exports = function (grunt) {
  grunt.initConfig({
    cssmin: {
      compress: {
        files: {
          'dest/car.min.css': [
          "src/car.css",
          "src/car01.css"
        ]
        }
      }
    }
  });

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

}

如此一來我們便可以壓縮合並CSS檔案了:

$ grunt cssmin --debug
Running "cssmin:compress" (cssmin) task
[D] Task source: d:\grunt\node_modules\grunt-contrib-cssmin\tasks\cssmin.js
File dest/car.min.css created.

移動打包檔案

其實,grunt本身具有這樣的功能,但是我們實際專案重會出現這種可能:

我們核心框架會有一套壓縮程式碼,並且會在對應目錄生成檔案用於釋出,但是這個地方的許可權對各個頻道團隊是不可見的

所以,我們在各個頻道的公共資料夾內應該將剛剛的檔案給複製過去,這塊程式碼其實很簡單,不需要任何新知識都能實現:

我們這裡依舊採用昨天的require相關的程式碼,但是一有個不同的地方就是,我們要同時在D盤的common資料夾中生成該檔案

這個程式碼其實比較簡單,這裡我們先介紹一個新的外掛copy

grunt-contrib-copy

該外掛用於複製檔案到你想要的資料夾處

grunt.initConfig({ copy: {
  main: {
    flatten: true,
    src: 'src/*.js',
    dest: 'dest/'
  }
}
});

這段程式碼就會將src中的js檔案搞到dest裡面,並且新建src資料夾:

$ grunt copy
Running "copy:main" (copy) task
Copied 7 files

若是不想複製資料夾只要檔案應該這樣幹:

grunt.initConfig({ copy: {
  main: {
    flatten: true,
    //    filter: 'isFile',
    expand: true,
    src: 'src/**.js',
    dest: 'dest/'
  }
}
});

這塊完了,我們就來移動打包檔案至D盤了

移動打包檔案

這個時候程式碼這樣寫就好(也許移動前我們還想將其資料夾裡面的東西銷燬,暫時不考慮了)

module.exports = function (grunt) {

  grunt.initConfig({ copy: {
    main: {
      //      flatten: true,
      //      expand: true,
      src: 'dest/**.js',
      dest: 'd:/common/'
    }
  }
  });

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-requirejs');

  grunt.registerTask('build', 'require demo', function () {

    //第一步,讀取配置資訊
    var cfg = grunt.file.readJSON('cfg.json');
    cfg = cfg.requirejs;
    grunt.config.set('requirejs', { test: cfg });

    //第二步,設定引數
    grunt.log.debug('引數:' + JSON.stringify(grunt.config()));

    //第三步跑任務
    grunt.task.run(['requirejs']);

  });

  grunt.registerTask('default', 'test demo', ['build', 'copy']);

}
Running "build" task

Running "requirejs:test" (requirejs) task
>> Tracing dependencies for: d:/grunt/dest/libs.js
>> Uglifying file: d:/grunt/dest/libs.js
>> d:/grunt/dest/libs.js
>> ----------------
>> d:/grunt/src/zepto.js
>> d:/grunt/src/underscore.js
>> d:/grunt/src/backbone.js
>> d:/grunt/src/test01.js
>> d:/grunt/src/require.text.js
>> text!src/demo01.html

Running "copy:main" (copy) task
Copied 8 files

關於移動相關的知識點暫時介紹到這裡,我們進入下一話題

分支/頻道處理

我們在實際專案重會遇到這種情況,我們一個主幹分支上可能拉出很多分支完成不同的功能,而各個分支就有那麼一點點不同,那麼這個時候打包工具該怎麼辦呢?

我們一般是這樣處理的:

① 首先全域性只會有一個打包工具

② 其次每一個分支都會有一個gruntCfg.json的配置檔案,儲存相關的打包資訊

③ 每次打包時候便把響應的分支列印到各自的dest目錄裡面

為了模擬這一情況我們將grunt打包相關的檔案放到D盤的grunt目錄裡面,並在D盤新建gruntDemo目錄

然後我們在gruntDemo中建立一個專案,並且為這個專案拉一個分支,比如現在專案是地demo01與demo02

現在檔案結構如下:

D:\GRUNTDEMO
├─demo01
│  │  gruntCfg.json
│  │
│  └─src
│          backbone.js
│          require.js
│          require.text.js
│          test01.js
│          test02.js
│          underscore.js
│          zepto.js
│
└─demo02
    │  gruntCfg.json
    │
    └─src
            backbone.js
            require.js
            require.text.js
            test01.js
            test02.js
            underscore.js
            zepto.js

這個時候,要實現功能最好的方法就是寫自定義任務了,其它方案不好使,這個時候起配置檔案也需要有一定修改,比如其中的路徑需要加入引數資訊

{
  "requirejs": {
    "options": {
      "baseUrl": "<%= config.srcDir %>",
      "paths": {
        "$": "src/zepto",
        "_": "src/underscore",
        "B": "src/backbone",
        "test": "src/test01",
        "text": "src/require.text"

      },
      "include": [
        "$",
        "_",
        "B",
        "test",
        "text!src/demo01.html"
        ],
        "out": "<%= config.destDir %>/libs.js"
      }
  }
}

這個時候initConfig相關資訊時候,首先得傳入path依賴的檔案目錄,以及輸出的檔案目錄

module.exports = function (grunt) {

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

  //channel為頻道名稱,project為專案名稱,這裡對應gruntDemo,branch為其分支,預設與grunt目錄為平行關係,佛則package.json裡面應該有配置資訊
  grunt.registerTask('build', 'require demo', function (channel, project, branch) {

    var path = '../' + channel + '/' + project + branch;
    grunt.log.debug('path: ' + path);

    //第一步,讀取配置資訊
    var cfg = grunt.file.readJSON(path + '/gruntCfg.json');
    cfg = cfg.requirejs;

    grunt.config.set('config', {
      srcDir: path,
      destDir: path + '/dest'
    });

    grunt.config.set('requirejs', { main: cfg });

    //第二步,設定引數
    grunt.log.debug('param: ' + JSON.stringify(grunt.config()));

    //第三步跑任務
    grunt.task.run(['requirejs']);

  });

  grunt.registerTask('default', 'test demo', ['build', 'copy']);

}

於是我們第一步工作成功了:

$ grunt build:gruntDemo:demo:02 --debug
Running "build:gruntDemo:demo:02" (build) task
[D] Task source: d:\grunt\Gruntfile.js
[D] path: ../gruntDemo/demo02
[D] param: {"config":{"srcDir":"../gruntDemo/demo02","destDir":"../gruntDemo/dem
o02/dest"},"requirejs":{"main":{"options":{"baseUrl":"../gruntDemo/demo02","path
s":{"$":"src/zepto","_":"src/underscore","B":"src/backbone","test":"src/test01",
"text":"src/require.text"},"include":["$","_","B","test","text!src/demo01.html"]
,"out":"../gruntDemo/demo02/dest/libs.js"}}}}

Running "requirejs:main" (requirejs) task
[D] Task source: d:\grunt\node_modules\grunt-contrib-requirejs\tasks\requirejs.j
s
>> Tracing dependencies for: d:/gruntDemo/demo02/dest/libs.js
>> Uglifying file: d:/gruntDemo/demo02/dest/libs.js
>> d:/gruntDemo/demo02/dest/libs.js
>> ----------------
>> d:/gruntDemo/demo02/src/zepto.js
>> d:/gruntDemo/demo02/src/underscore.js
>> d:/gruntDemo/demo02/src/backbone.js
>> d:/gruntDemo/demo02/src/test01.js
>> d:/gruntDemo/demo02/src/require.text.js
>> text!src/demo01.html

如果改變一下任務命令呢:

grunt build:gruntDemo:demo:01 --debug

結果證明也是沒有問題的,這個地方我就不貼出來了,各位自己去試試,我們分支處理一塊暫時到這裡

頻道處理其實我們這裡已經做了,第一個引數是頻道,第二個引數是專案,第三個引數為分支,所以頻道相關我們暫時就不說了

native與HTML5打包

最後讓我們來看看如何打包native檔案,native檔案的打包其實與打包HTML5的方式類似,只不過我們這裡需要一點點配置,讓一個專案可以打包成不同的效果

仍然以上面demo01為例,他的配置檔案可能就需要做一定調整:

{
    "requirejs": {
        "options": {
            "baseUrl": "<%= config.srcDir %>", 
            "paths": {
                "$": "src/zepto", 
                "_": "src/underscore", 
                "B": "src/backbone", 
                "test": "src/test01", 
                "text": "src/require.text"
            }, 
            "web": {
                "include": [
                    "$", 
                    "_", 
                    "B", 
                    "test"
                ], 
                "out": "<%= config.destDir %>/libs.js"
            }, 
            "app": {
                "include": [
                    "$", 
                    "_", 
                    "B", 
                    "test", 
                    "text!src/demo01.html"
                ], 
                "out": "<%= config.destDir %>/libs_app.js"
            }
        }
    }
}

這裡為了表現一點web與native的不同,我特意將web中少包含一個text檔案,具體還得各位專案中去實踐

如此一來,我們的程式碼需要做些許調整:

module.exports = function (grunt) {

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

  //type 打包app包還是web包,channel為頻道名稱,project為專案名稱,這裡對應gruntDemo,branch為其分支,預設與grunt目錄為平行關係,佛則package.json裡面應該有配置資訊
  grunt.registerTask('build', 'require demo', function (type, channel, project, branch) {

    var path = '../' + channel + '/' + project + branch;
    grunt.log.debug('path: ' + path);

    //第一步,讀取配置資訊
    var cfg = grunt.file.readJSON(path + '/gruntCfg.json');
    cfg = cfg.requirejs.options;

    grunt.config.set('config', {
      srcDir: path,
      destDir: path + '/dest'
    });

    grunt.log.debug('param: ' + JSON.stringify(cfg));
    grunt.log.debug('param: ' + cfg[type]['include']);


    var taskCfg = {};
    taskCfg.options = {};
    taskCfg.options.baseUrl = cfg.baseUrl;
    taskCfg.options.paths = cfg.paths;
    taskCfg.options['include'] = cfg[type]['include'];
    taskCfg.options.out = cfg[type].out;


    grunt.config.set('requirejs', { main: taskCfg });

    //第二步,設定引數
    grunt.log.debug('param: ' + JSON.stringify(grunt.config()));

    //第三步跑任務
    grunt.task.run(['requirejs']);

  });

  grunt.registerTask('default', 'test demo', ['build', 'copy']);

}

於是便可以運行了!!!

$ grunt build:app:gruntDemo:demo:01 --debug
Running "build:app:gruntDemo:demo:01" (build) task
[D] Task source: d:\grunt\Gruntfile.js
[D] path: ../gruntDemo/demo01
[D] param: {"baseUrl":"<%= config.srcDir %>","paths":{"$":"src/zepto","_":"src/u
nderscore","B":"src/backbone","test":"src/test01","text":"src/require.text"},"we
b":{"include":["$","_","B","test"],"out":"<%= config.destDir %>/libs.js"},"app":
{"include":["$","_","B","test","text!src/demo01.html"],"out":"<%= config.destDir
 %>/libs_app.js"}}
[D] param: $,_,B,test,text!src/demo01.html
[D] param: {"config":{"srcDir":"../gruntDemo/demo01","destDir":"../gruntDemo/dem
o01/dest"},"requirejs":{"main":{"options":{"baseUrl":"../gruntDemo/demo01","path
s":{"$":"src/zepto","_":"src/underscore","B":"src/backbone","test":"src/test01",
"text":"src/require.text"},"include":["$","_","B","test","text!src/demo01.html"]
,"out":"../gruntDemo/demo01/dest/libs_app.js"}}}}

Running "requirejs:main" (requirejs) task
[D] Task source: d:\grunt\node_modules\grunt-contrib-requirejs\tasks\requirejs.j
s
>> Tracing dependencies for: d:/gruntDemo/demo01/dest/libs_app.js
>> Uglifying file: d:/gruntDemo/demo01/dest/libs_app.js
>> d:/gruntDemo/demo01/dest/libs_app.js
>> ----------------
>> d:/gruntDemo/demo01/src/zepto.js
>> d:/gruntDemo/demo01/src/underscore.js
>> d:/gruntDemo/demo01/src/backbone.js
>> d:/gruntDemo/demo01/src/test01.js
>> d:/gruntDemo/demo01/src/require.text.js
>> text!src/demo01.html

結語

我們這個星期花了三天時間一起學習了grunt打包相關的知識點,需要這些知識對您有用,搞這個東西還花費了不少心血呢!!!

若是文中有誤請一併提出,後續若是這塊有所得我們再一起總結吧

原來是分成三段,這裡將之合一方便各位連貫閱讀,篇幅大,記得點贊

相關推薦

grunt整合30分鐘學會使用grunt打包前端程式碼

grunt 是一套前端自動化工具,一個基於nodeJs的命令列工具,一般用於:① 壓縮檔案② 合併檔案③ 簡單語法檢查 對於其他用法,我還不太清楚,我們這裡簡單介紹下grunt的壓縮、合併檔案,初學,有誤請包涵 準備階段 1、nodeJs環境 因為grunt是基於nodeJs的,所以首先各位需要安裝

grunt第一彈30分鐘學會使用grunt打包前端程式碼

前言 以現在前端js激增的態勢,一個專案下來幾十個js檔案輕輕鬆鬆對於複雜一點的單頁應用來說,檔案上百簡直是家常便飯,那麼這個時候我們的js檔案應該怎麼處理呢?另外,對於css檔案,又該如何處理呢??這些都是我們實際工作中要遇到的問題,比如我們現在框架使用zepto、backbone、underscore我

公眾號系列分鐘學會SAP F1技巧

origin 根據 http 想要 www. 繼續 內容 應該 logs 公眾號:SAP Technical 本文作者:matinal 原文出處:http://www.cnblogs.com/SAPmatinal/ 原文鏈接:【公眾號系列】兩分鐘學會SAP F1技巧

網站搭建30分鐘輕鬆搭建網站應用

30分鐘輕鬆搭建網站應用 今天給大家分享如何30分鐘快速搭建網站。使用免費開源個人部落格建站工具WordPress部署部落格網站,最終實現:管理員-部署網站並進行日常運維、訪客-通過網際網路訪問部落格、瀏覽文章等。 先看看簡單的網站部署架構示意圖: 具體的應用部署分為以下幾個大的步驟。

SpringBoot整合Mybatis非註解

接上文:SpringBoot整合Mybatis【註解版】 一、專案建立 新建一個工程 ​ 選擇Spring Initializr,配置JDK版本 ​ 輸入專案名 ​  選擇構建web專案所需的

C++1130分鐘瞭解C++11新特性

什麼是C++11 C++11是曾經被叫做C++0x,是對目前C++語言的擴充套件和修正,C++11不僅包含核心語言的新機能,而且擴充套件了C++的標準程式庫(STL),併入了大部分的C++ Technical Report 1(TR1)程式庫(數學的特殊函式除外)。 C++11包括大量的新特性

原創30分鐘入門 github

很久沒更新了,這篇文章重點在github的入門使用,讀者可以下載github for windows shell,邊看邊操作,加深印象。 好了,30分鐘的愉快之旅開始吧: 一、github使用的注意事項: 1.對於某一次更新提交,必須要有這次操作的commit操作,git commit -m

30分鐘學會用scikit-learn的基本回歸方法(線性、決策樹、SVM、KNN)和整合方法(隨機森林,Adaboost和GBRT)

注:本教程是本人嘗試使用scikit-learn的一些經驗,scikit-learn真的超級容易上手,簡單實用。30分鐘學會用呼叫基本的迴歸方法和整合方法應該是夠了。 本文主要參考了scikit-learn的官方網站 前言:本教程主要使用了numpy的最最基

30分鐘學會vim之vimtutor(雙語

=============================================================================== = W e l c o m e t o t h e V I M T u t o r - Version 1.7 = 歡迎使用VIM教程 1.7版 =

30分鐘學會如何使用Shiro

springmvc+mybatis dubbo+zookeeper restful redis分布式緩存 shiro kafka 一、架構要學習如何使用Shiro必須先從它的架構談起,作為一款安全框架Shiro的設計相當精妙。Shiro的應用不依賴任何容器,它也可以在JavaSE下使用。但

30分鐘學會如何使用Shiro(轉)

字段 col inf lan getc 含義 掌握 ide 包含 本文轉自http://www.cnblogs.com/learnhow/p/5694876.html 感謝作者 本篇內容大多總結自張開濤的《跟我學Shiro》原文地址:http://jinnianshilo

全幹貨 5 分鐘帶你看懂 Docker !

service stop 技術分享 address article 快速 停止 容量 rom 歡迎大家前往騰訊雲社區,獲取更多騰訊海量技術實踐幹貨哦~ 作者丨唐文廣:騰訊工程師,負責無線研發部地圖測試。 導語:Docker,近兩年才流行起來的超輕量級虛擬機,它可以讓你輕松

30分鐘學會如何使用Shiro(轉)

dex user false fin hiberna bean overflow getc mis 本篇內容大多總結自張開濤的《跟我學Shiro》原文地址:http://jinnianshilongnian.iteye.com/blog/2018936我並沒有全部看完,只是

小白30分鐘學會網頁采集基礎教程

網頁采集首先,以某個多頁(需要自動翻頁)表格數據的采集為例,先演示一次網頁采集的完整的過程:點擊從頭播放完整動圖演示這裏使用的是八爪魚,依次點擊表格某一行的每個字段,可以自動識別出其他所有數據行,並自動創建循環列表;點擊翻頁按鈕,選擇“循環點擊下一頁”動作,就能自動創建翻頁循環。網頁信息爪取相關的工具有很多,

30分鐘學會iOS 11開發環境xcode 9圖文教程

iOS 11關註微信公眾號【異步圖書】每周送書Xcode是一款功能全面的應用程序,通過此工具可以輕松輸入、編譯、調試並執行Objective-C程序。如果想在Mac上快速開發iOS應用程序,則必須學會使用這個強大的工具的方法。在本文容中,將詳細講解Xcode 9開發工具的基本知識,為讀者步入本書後面知識的學習

3dmax2013-20193dsmax破解破解中文版(付破解教程)

3Dmax3dmax2013-2019【3dsmax破解版】破解中文版界面語言:中文版/英文版軟件大小:5.32GB運行環境:Win2003,WinXP,Win2000,Win9X,Win7運行支持:64位

CAD2011-2019下載免費中文版CAD2019破解最新cad2019破解-

auto cad界面語言:中文版軟件大小:2.81GB運行環境:Win2003,WinXP,Win2000,Win9X,Win7運行支持:64位/32位下載地址:AUTO CAD (百度網盤)密碼: wmsgCAD2018下載免費中文版【CAD2018破解版】最新cad2018破解版介紹CAD2018免費中

織夢聯動篩選單選-支援手機站使用

警告:操作之前先備份你的程式這2個檔案。 /include/arc.listview.class.php /include/extend.func.php 織夢聯動篩選【單選版】下載 https://pan.baidu.com/s/1lusq3thwEpzA6yLWeHvcww 密碼: a

織夢聯動篩選單選-支持手機站使用

istview dede www. tro oba 地方 arc lte text 警告:操作之前先備份你的程序這2個文件。 /include/arc.listview.class.php /include/extend.func.php 織夢聯動篩選【單選版】下載 h

面向物件林老師:繼承的原理(五)

一、經典類 經典類:沒有繼承object的類,以及它的子類都稱之為經典類 1、python2.x 在python2中-》經典類:沒有繼承object的類,以及它的子類都稱之為經典類 class Foo: pass class Bar(Foo): pass 二、新式類 1