Compiling coffeescript files with grunt

匆匆过客 提交于 2019-12-08 00:21:37

问题


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:

File structure after compile:

Compilation message:


回答1:


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


来源:https://stackoverflow.com/questions/23905751/compiling-coffeescript-files-with-grunt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!