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之类的都没来得及写,以后有时间会再补上来。

愿每天都是新的开始,愿何时何地都有一小片净土能安放下我的电脑,安放下隐隐躁动的心,潜龙勿用。

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