【问题标题】:Creating a file watcher for coffeescript with grunt使用 grunt 为咖啡脚本创建文件观察器
【发布时间】:2014-07-18 00:14:40
【问题描述】:

我正在尝试使用 grunt watch 插件 (https://www.npmjs.org/package/grunt-contrib-watch) 创建自定义文件监视程序。我正在为咖啡脚本文件编写编译脚本,以便在更改时对其进行编译。这是基本配置。

grunt.initConfig(
    pkg: grunt.file.readJSON 'package.json'
    watch:
      cofee_files:
        files: ['client/**/*.coffee'],
        tasks: ['start'],
        options:
          spawn: false,

grunt.registerTask( 'start', 'starting coffee compilation', (filepath)->
    console.log(filepath)

我需要获取文件路径作为输入,以便能够对文件执行编译并将输出保存在相对于源咖啡脚本文件的文件路径的目录中。在我上面编写的代码中,传递的文件路径值未定义 - 我可以在日志输出中看到。请帮我获取修改后文件的文件路径,以便我可以相应地动态配置coffeescript编译器。

【问题讨论】:

    标签: gruntjs grunt-contrib-watch grunt-contrib-coffee


    【解决方案1】:

    您需要为 watch 事件注册一个处理程序。在那里您将获得可用于配置咖啡任务的文件路径:

    (代码未经测试,但我想你明白了)

    path = require 'path'
    
    grunt.initConfig(
      pkg: grunt.file.readJSON 'package.json'
    
      watch:
        cofee_files:
          files: ['client/**/*.coffee'],
          tasks: ['start'],
          options:
            spawn: false,
      coffee:
        compile: 
          files: []
    
    
      grunt.event.on 'watch', (action, filepath) ->
        # modify your coffee task here
        newCoffeeConfig = 
          cwd: path.dirname(filepath)
          src: path.basename(filepath)
          dest: path.dirname(filepath)
          ext. '.js' 
    
        grunt.config.get('coffee:compile.files').push newCoffeeConfig
        grunt.task.run 'coffee:compile'
    

    【讨论】:

    • 对不起。我之前得到了一个误报。该代码会产生一个错误:Fatal error: Cannot call method 'push' of undefined。我也尝试编译为grunt.config.get('coffee:compile'),这也不起作用。能否提供语法准确的代码?
    • grunt.event.on 'watch' 的标识是错误的,我更正了。此外,SO 是一个帮助您理解事物的板,但不是用来做您的工作的!一定是你自己做的某种转移……
    猜你喜欢
    • 1970-01-01
    • 2011-09-27
    • 2012-04-27
    • 2015-10-26
    • 2014-06-29
    • 2012-05-15
    • 2014-10-20
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多