【问题标题】:Custom CoffeeScript compilation with GruntJS使用 GruntJS 进行自定义 CoffeeScript 编译
【发布时间】:2015-01-15 07:56:03
【问题描述】:

我有一个Gruntfile,它从某个文件夹中获取所有*.coffee文件,并将它们编译为JS文件,保持相同的文件夹结构(如果有的话)。

所以文件夹结构如下:

scripts
|--widgets
|    |--a.coffee
|--vendor
|    |--b.coffee
|--c.coffee
|--d.coffee

它将生成相同的文件夹结构,但使用 JS 文件而不是 Coffeescript 文件。我想为widgets 文件夹和c.coffee 文件制定单独的规则,即。我想将widgetsc.coffee 的所有内容编译到一个文件中。

如何从 grunt 对象的 files 属性中排除一个文件和一个文件夹?这是我目前正在运行的代码:

files: [{
    expand: true,
    cwd: '<%= params.app %>/scripts',
    src: '{,*/}*.{coffee,litcoffee,coffee.md}',
    dest: '.tmp/scripts',
    ext: '.js'
}]

我还看到有两种语法可以声明files。一个作为对象,一个作为数组(我上面有)。有什么区别?在我的情况下,其他声明会更好地帮助我吗?

【问题讨论】:

  • 您是否需要在src 定义中只深入一层?在我的回答中,我将其扩展到“没有或很多级别”,因为它更易于阅读。

标签: coffeescript gruntjs


【解决方案1】:

documentation on configuring grunt tasks 有一些关于您想要的内容。实际上,有四种方法可以定义文件属性,其中一种已被弃用。

这里是Gruntfile.coffee,因为它更短。将 File Arrays Formatcompile 子任务的排除模式和 Compact Format 用于 compileJoined 子任务。我希望你使用grunt-contrib-coffeegrunt-coffee 已经停止维护将近两年了,似乎没有 join 选项。

module.exports = (grunt) ->
  grunt.initConfig
    params: app: '.' # ignore this, it's just that this file works as expected.

    coffee:
      compile:
        files: [
          cwd: '<%= params.app %>/scripts'
          expand: yes
          src: ['**/*.{coffee,litcoffee,coffee.md}'   # everything coffee in the scripts dir
            '!c.coffee'        # exclude this
            '!widgets/**/*']   # and these
          dest: '.tmp/scripts'
          ext: '.js'
          extDot: 'first' # to make .js files from .coffee.md files
          ]

       compileJoined:
         options: join: yes
         # sadly you can't use expand here, so you'll have to do cwd "by hand".
         src: [
           '<%= params.app %>/scripts/c.coffee'
           '<%= params.app %>/scripts/widgets/**/*.{coffee,litcoffee,coffee.md}'
           ]
         dest: '.tmp/special.js'

  grunt.loadNpmTasks 'grunt-contrib-coffee'

这是script 的一个小输出,它似乎有效:

$ tree scripts
scripts
├── c.coffee
├── d.coffee
├── vendor
│   └── b.coffee
└── widgets
    └── a.coffee

2 directories, 4 files
$ rm -rf .tmp
$ grunt coffee
Running "coffee:compile" (coffee) task
>> 2 files created.

Running "coffee:compileJoined" (coffee) task
>> 1 files created.

Done, without errors.
$ tree .tmp
.tmp
├── scripts
│   ├── d.js
│   └── vendor
│       └── b.js
└── special.js

2 directories, 3 files
$ cat scrips/c.coffee
variableInC_coffee = "a variable"
$ cat scripts/widgets/a.coffee

variableInC_coffee = variableInC_coffee.replace /\s+/, '_'
$ cat .tmp/special.js
(function() {
  var variableInC_coffee;

  variableInC_coffee = "a variable";

  variableInC_coffee = variableInC_coffee.replace(/\s+/, '_');

}).call(this);

【讨论】:

  • 是的,这就是我最终做的,我只是忘了在这里添加一个答案。另一方面,你刚刚给了我一个很好的目录树构建工具,我需要它,所以对此表示赞赏:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
  • 2013-10-14
  • 2012-08-10
  • 2019-01-08
  • 1970-01-01
相关资源
最近更新 更多