Grunt: 監聽文件修改及重啓node服務器

Grunt簡介

grunt簡介截圖

Grunt是一個基於node.js的自動化構建工具,合理的設置grunt能幫助前端開發人員輕鬆完成諸如less、coffeescript編譯,css、JavaScript壓縮等基礎而繁瑣的工作,更多高級用法請自行探究。

因爲公司這邊用的是基於百度fis3開發的自動化構建工具,所以沒仔細研究Grunt,今天做項目的時候,因爲每次修改完文件都要重啓服務器才能看到效果,所以簡單地設置一下Grunt,滿足了基本需求,如果後續深入研究,會繼續更新這篇博客。

Grunt配置

①安裝grunt及grunt插件

在package.json文件如下:

{
  "name": "demo",
  "version": "1.0.0",
  "description": "simple demo for learning",
  "main": "index.js",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.4",
    "grunt": "~0.4.5",
    "grunt-contrib-watch": "~0.5.3",
    "grunt-develop": "~0.4.0"
  }
}

如上所示,在package.json文件的dependencies裏面添加:

    "grunt": "~0.4.5",
    "grunt-contrib-watch": "~0.5.3",
    "grunt-develop": "~0.4.0"

得益於node的依賴管理機制,添加grunt超級簡單,添加完後,在項目根目錄執行下面命令,安裝grunt及grunt插件即可:

npm install

②配置Grunt

在項目根目錄新建Gruntfile.js,如下:

module.exports = function (grunt) {
  grunt.initConfig({
    watch: {
      js: {
        files: ['index.js'],  //can use regex to match file
        tasks: ['develop'],
        options: { 
          nospawn: true   //is important !You need to specify nospawn : true in your watch task configuration so that the called tasks run in the same context.
        }
      }
    },
    develop: {
      server: {
        file: 'index.js'  //the file to start server
      }
    }
  });

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

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

最近

自古風雲多變幻。最近兩個月發生太多事了,也很久沒寫博客了,之前學的sidekiq,rails配置郵件發送,搜索引擎solr之類的都沒來得及寫,以後有時間會再補上來。

願每天都是新的開始,願何時何地都有一小片淨土能安放下我的電腦,安放下隱隱躁動的心,潛龍勿用。

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