初學grunt

check the official docs first


grunt到底可以做些什麼?

  • 最小化文件 uglify
  • 文件整合 concat

install node.js && npm

install git(optional),

install vscode editor, in terminal select default shell ( from cmd to git bash )

for example, use following command to copy the repository to your pc:

git clone https://github.com/cowboy/jquery-tiny-pubsub

cd to the folder “jquery-tiny-pub”

use command npm install to install all dependencies


Gruntfile組成,一般用Gruntfile.js。

組成爲:

  1. wrapper function 包裝器函數:

module.exports = function(grunt) {}

這個算是入口,當在terminal中輸入grunt時,node知道加載這個文件。

  1. Project and task configuration 項目和任務配置

    如: pkg: grunt.file.readJSON('package.json'), uglify: {}

    文檔中寫到:

    In this example, grunt.file.readJSON('package.json') imports the JSON metadata stored in package.json into the grunt config.

    我的理解:

    pkg的全稱是package。 grunt這個對象,後面跟一個file屬性,然後一個readJSON方法,應該都是grunt自定義的, 可能只有查看源文件才能明白作者是怎麼設計的。看名字readJSON就知道是讀json文件去了。

    那麼讀文件的目的是什麼?讀什麼內容呢?

    文檔中寫到:

    Because <% %> template strings may reference any config properties, configuration data like filepaths and file lists may be specified this way to reduce repetition.
    

    這個模板語法可能引用任何配置屬性,爲了減少重複,配置數據如文件路徑和文件列表可能用這種方式來指定

    You may store any arbitrary data inside of the configuration object, and as long as it doesn't conflict with properties your tasks require, it will be otherwise ignored. 
    
    Also, because this is JavaScript, you're not limited to JSON;
    
    you may use any valid JS here. 
    
    You can even programmatically generate the configuration if necessary.
    

    內容等會再看,先看後面的

    示例如下:

    // Project configuration.
    grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),
      uglify: {
        options: {
          banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
        },
        build: {
          src: 'src/<%= pkg.name %>.js',
          dest: 'build/<%= pkg.name %>.min.js'
        }
      }
    });
    

    這裏提到了模版字符串<% %>,一開始聽着名字還以爲是js中的模板字符串呢,這看不起不像,爲什麼呢,可能因爲*``*是es6的語法吧,Template literals。至於這個模版字符串怎麼定義的,估計只能查看源碼了。然後查看api吧,grunt.template

    <%= pkg.name %>應該指的是,去package.json裏面去找name這個key。即{“name”: ??},如我自定義的這個name是gruntproject, 然後我在根目錄新建一個文件夾src,在裏面在建一個文件gruntproject.js。這個src: 'src/<%= pkg.name %>.js'就是原文件的位置。然後dest: 'build/<%= pkg.name %>.min.js'就是目標文件的位置和文件名。當我在terminal中輸入grunt uglify,就會輸出下面的Logs

     Running "uglify:build" (uglify) task
     
     > > 1 file created 30 B → 63 B
     
     Done.
    

    再看根目錄,就會發現有個文件夾build自動生成了,裏面有一個文件gruntproject.min.js。打開這個文件,代碼如下:

        /*! gruntproject 2019-08-02 */
    
        +gruntproject.js裏面的代碼
    

    所以這個{options: {banner: ??}}的意思,banner是橫幅的意思,然後會在新文件的第一行開始寫入,然後基本格式是一個字符串,如“某個字符串\n”\n是換行的意思。可以看出模版字符串裏面的代碼是會先解析的,解析完後再合併到字符串裏面。

  2. Loading Grunt plugin and tasks 加載grunt插件和任務

    是不是說需要grunt插件來處理特定的任務,及uglify任務就必須要grunt-contrib-uglify插件來處理。這時候pkg應該排上用處了

  3. Custom tasks 自定義任務

    首要要設置一個默認的任務,即告訴grunt,如果我沒有指定要做哪個任務,那麼就做這個default任務

    實例代碼塊:

    // Default task(s).
    grunt.registerTask('default', ['uglify']);
    

    文檔中寫到:

    You can configure Grunt to run one or more tasks by default by defining a default task. In the following example, running grunt at the command line without specifying a task will run the uglify task. This is functionally the same as explicitly running grunt uglify or even grunt default. Any number of tasks (with or without arguments) may be specified in the array.

    即在這個實例中,我可以用grunt defaultgrunt uglify來執行default任務uglify。

    如果我想添加更多的任務,那麼就直接在這個數組裏面加就可以了

    文檔中寫到:

    If your project requires tasks not provided by a Grunt plugin, you may define custom tasks right inside the Gruntfile. For example, this Gruntfile defines a completely custom default task that doesn't even utilize task configuration:
    

    如果某些情況,沒有相應的插件可以處理,那麼就可以直接在這個文件裏定義。

    如下面這個列子就完全沒有使用第二步中的任務配置

    module.exports = function(grunt) {
    
      // A very basic default task.
      grunt.registerTask('default', 'Log some stuff.', function() {
        grunt.log.write('Logging some stuff...').ok();
      });
    
    };
    

    通過查文檔api中的grunt.taskgrunt.registerTaskgrunt.task.registerTask的縮寫, 然後這裏用到了3個參數,用的是這個grunt.task.registerTask(taskName, description, taskList)。然後grunt.log的api中的一個用法grunt.log.write(msg), 看是要看api怎麼寫的,比如grunt.log.write和grunt.log.writeln的區別。

minify files:

最小化文件,比如jquery文件的開發版和最小化版

uglify task, grunt-contrib-uglify plugin

任務名叫做uglify,要用npm install grunt-contrib-uglify --save-dev安裝插件到devDependencies

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