使用grunt编译coffeescript文件

时间:2014-05-28 07:53:10

标签: coffeescript gruntjs grunt-contrib-coffee

我正在尝试编写一个grunt任务,使用grunt将大量.coffee文件编译为相应的.js文件和.map文件。我有一个咕噜咕噜的咖啡插件,但有一些问题:

  1. 它将所有文件编译到一个公共目标文件夹中,而不是将.js文件保存在与.coffee文件相同的文件夹中。
  2. 它将不同目录中同名的两个.coffee文件合并到目标目录中的一个文件中。
  3. 请帮助解决这些问题:

    Grunt插件:https://www.npmjs.org/package/grunt-contrib-coffee

    Gruntfile.coffee:

    module.exports = (grunt) ->
      grunt.initConfig(
        pkg: grunt.file.readJSON 'package.json'
        coffee:
          coffee_to_js:
            options:
              bare: true
              sourceMap: true
            expand: true
            flatten: true
            cwd: "client"
            src: ["**/*.coffee"]
            dest: 'client'
            ext: ".js"
      )
    
      #Load Tasks
      grunt.loadNpmTasks 'grunt-contrib-coffee'
      grunt.registerTask('compile', ['coffee']);
    
      null
    

    编译Gruntfile.js

    module.exports = function(grunt) {
      grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        coffee: {
          coffee_to_js: {
            options: {
              bare: true,
              sourceMap: true
            },
            expand: true,
            flatten: true,
            cwd: "client",
            src: ["**/*.coffee"],
            dest: 'client',
            ext: ".js"
          }
        }
      });
      grunt.loadNpmTasks('grunt-contrib-coffee');
      grunt.registerTask('compile', ['coffee']);
      return null;
    };
    

    编译前的文件结构:

    enter image description here

    编译后的文件结构:

    enter image description here

    编译信息:

    enter image description here

1 个答案:

答案 0 :(得分:6)

如果要维护JS编译的结构,应将flatten标志设置为false。见Grunt Configuring tasks - Building the files object dynamically

module.exports = (grunt) ->
  grunt.initConfig
    pkg: grunt.file.readJSON 'package.json'
    coffee:
      coffee_to_js:
        options:
          bare: true
          sourceMap: true
        expand: true
        flatten: false
        cwd: "client"
        src: ["**/*.coffee"]
        dest: 'client'
        ext: ".js"

  #Load Tasks
  grunt.loadNpmTasks 'grunt-contrib-coffee'
  grunt.registerTask 'compile', ['coffee']

这是不平整时的输出,我相信是你之后的:

$ grunt compile
Running "coffee:coffee_to_js" (coffee) task
File client/main.js created.
File client/main.js.map created (source map).
File client/models/question.js created.
File client/models/question.js.map created (source map).
File client/views/question.js created.
File client/views/question.js.map created (source map).