使用grunt实现nodejs服务器自动重启

nodejs开发在修改代码后,总是需要重启服务器才能看到即时效果,开发起来十分繁琐,效率低下,通过配置grunt就可以实现监听文件改动,实现服务器自动重启的目的。

在项目根目录新建Gruntfile.js文件。

然后分别需要安装两个插件grunt-nodemongrunt-concurrent

grunt-nodemon用来监视文件改动,并且实现服务器重启

grunt-concurrent实现添加多个grunt任务

所以最终Gruntfile.js的代码是这样,具体的配置参数可以参考npm上的文档说明

module.exports = function (grunt) {

  grunt.initConfig({

    nodemon: {
      dev: {
        script: 'app.js',
        options: {
          args: [],
          nodeArgs: ['--inspect'],
          ignore: ['README.md', 'node_modules/**', '.DS_Store'],
          ext: 'js',
          watch: ['./'],
          delay: 1000,
          env: {
            PORT: 3000
          },
          cwd: __dirname
        }
      }
    },

    concurrent: {
      target: {
        tasks: ['nodemon'],
        options: {
          logConcurrentOutput: true
        }
      }
    }
  })

  grunt.loadNpmTasks('grunt-nodemon')
  grunt.loadNpmTasks('grunt-concurrent')

  grunt.option('force', true)

  grunt.registerTask('default', ['concurrent:target'])
}
如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注