EternallyCurious
EternallyCurious

Reputation: 2415

Compiling coffeescript files with grunt

I am trying to write a grunt task to compile numerous .coffee files to corresponding .js files and .map files using grunt. I have the grunt coffee plugin, but there are some problems:

  1. It compiles all files into one common destination folder instead of keeping the .js files in same folder as the .coffee file.
  2. It merges two .coffee files of the same name in different directories into one file in the destination directory.

Please help solving these:

Grunt plugin: 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

Compiled 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;
};

File structure before compile:

enter image description here

File structure after compile:

enter image description here

Compilation message:

enter image description here

Upvotes: 2

Views: 5195

Answers (1)

maxbeatty
maxbeatty

Reputation: 9325

If you want to maintain the structure of where your JS is compiled, you should set the flatten flag to false. See 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']

This is the output when not flattened which I believe is what you're after:

$ 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).

Upvotes: 6

Related Questions