【问题标题】:Grunt: How to build the files object dynamicallyGrunt:如何动态构建文件对象
【发布时间】:2015-03-04 05:50:57
【问题描述】:

我必须在这里遗漏一些非常简单的东西。我正在尝试编写一个处理文件的函数任务。 Grunt API 文档提到您可以[动态构建文件对象],但由于某种原因,我无法让它工作。我的 Gruntfile.js 文件的简化版本如下所示:

module.exports = function(grunt) {
    grunt.initConfig({
        proj: {
            build: {
                files: [{
                    expand: true,
                    cwd: 'src',
                    src: ['**/*.js'],
                    dest: 'dist'
                }]
            }
        }
    });

    grunt.registerTask('proj', function(){
        var files = grunt.config('proj.build.files');
        console.log(files);
    });
};

我希望日志显示从 src 目录到 dist 目录的文件映射列表。实际记录的是配置中的对象 proj.build.files,如下所示:

Running "proj:build" task
[ { expand: true, cwd: 'src', src: [ '**/*.js' ], dest: 'dist' } ]

Done, without errors.

API 文档仅在其他任务方面讨论这种类型的配置。我尝试通过 uglify 任务查看文件映射是如何检索的,但我无法弄清楚。

【问题讨论】:

标签: node.js gruntjs config


【解决方案1】:

这是我发现的为 Grunt 任务动态构建文件集的解决方法:

uglify: {
    app: {
        files: [{
            src: '{<%= _prefixSrc(pkg.target, pkg.resources.js) %>}', // Note the brackets!
            dest: '<%= pkg.target %>min/<%= pkg.name %>.min.js'
        }]
    }
},
_prefixSrc: function(prefix, files) {
    return files.map(function(file){
        return prefix + file;
    });
},

另请参阅 GitHub 上的此问题/功能请求,如果您觉得有用,请随时发表评论:https://github.com/gruntjs/grunt/issues/1307

【讨论】:

    【解决方案2】:

    您可以使用重命名函数来更改文件名是文件对象,如下所示...

    build: {
      files: [{
        expand: true,
        cwd: 'src',
        src: ['**/*.js'],
        dest: 'dist',
        rename: function(dest, src) {
          /* 
             rename logic
             you will have access to src and dest name and can return desirect name from this function.
          */
          return src+123;
        }
     }]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-05
      • 2014-05-31
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 2012-10-11
      • 1970-01-01
      相关资源
      最近更新 更多