将src / dest位置重用于多个grunt concat操作

时间:2015-02-26 21:30:50

标签: gruntjs grunt-contrib-concat

我目前使用grunt-contrib-concat进行此设置:

concat: {
    injectedJs: {
        'dist/js/inject/beatportInject.js': ['src/js/thirdParty/jquery.js', 'src/js/inject/beatportInject.js'],
        'dist/js/inject/streamusInject.js': ['src/js/thirdParty/jquery.js', 'src/js/thirdParty/lodash.js', 'src/js/inject/streamusInject.js'],
        'dist/js/inject/streamusShareInject.js': ['src/js/thirdParty/jquery.js', 'src/js/thirdParty/lodash.js', 'src/js/inject/streamusShareInject.js'],
        'dist/js/inject/youTubeInject.js': ['src/js/thirdParty/jquery.js', 'src/js/thirdParty/lodash.js', 'src/js/inject/youTubeInject.js'],
        'dist/js/inject/youTubeIFrameInject.js': ['src/js/thirdParty/jquery.js', 'src/js/thirdParty/lodash.js', 'src/js/inject/youTubeIFrameInject.js']
    }
}

此代码有效,但这些字符串中显然有很多非DRY代码。

我希望通过表达我的事实来清理它:

  • 总是希望'dest'成为'dist / js / inject /'
  • 总是希望'src'以'src / js /'
  • 开头

所以,在我看来,我可以说出类似于这个伪代码的东西:

concat: {
    injectedJs: {
        files: [{
            expand: true,
            dest: 'dist/js/inject/',
            cwd: 'src/js'

            //'beatportInject.js': ['thirdParty/jquery.js', 'inject/beatportInject.js'],
            //'streamusInject.js': ['thirdParty/jquery.js', 'thirdParty/lodash.js', 'inject/streamusInject.js'],
            //'streamusShareInject.js': ['thirdParty/jquery.js', 'thirdParty/lodash.js', 'inject/streamusShareInject.js'],
            //'youTubeInject.js': ['thirdParty/jquery.js', 'thirdParty/lodash.js', 'inject/youTubeInject.js'],
            //'youTubeIFrameInject.js': ['thirdParty/jquery.js', 'thirdParty/lodash.js', 'inject/youTubeIFrameInject.js']
        }]
    }
}

我的想法在这一点上不尽如人意。这有可能通过Grunt实现,还是我需要重复一次?

1 个答案:

答案 0 :(得分:0)

请记住配置只是简单的javascript,因此最简单的解决方案不涉及黑客攻击Grunt只是

function prefix(fileConfig) {
    var newFileConfig = {};
    var distPrefix = 'dist/js/inject/';
    var srcPrefix = 'src/js/';

    for(var dest in fileConfig) {
        newFileConfig[distPrefix + dest] = srcPrefix + fileConfig[dest];
    }

    return newFileConfig;
}

grunt.initConfig({
    concat : {
        injectedJs : {
            files: [
                prefix({
                'beatportInject.js': ['thirdParty/jquery.js', 'inject/beatportInject.js'],
                'streamusInject.js': ['thirdParty/jquery.js', 'thirdParty/lodash.js', 'inject/streamusInject.js'],
                'streamusShareInject.js': ['thirdParty/jquery.js', 'thirdParty/lodash.js', 'inject/streamusShareInject.js'],
                'youTubeInject.js': ['thirdParty/jquery.js', 'thirdParty/lodash.js', 'inject/youTubeInject.js'],
                'youTubeIFrameInject.js': ['thirdParty/jquery.js', 'thirdParty/lodash.js', 'inject/youTubeIFrameInject.js']
            })
            ]
        }
    }
})

关于你的实际问题,连接脚本,你真正应该研究的东西似乎是Browserify或WebPack。这样可以省去很多麻烦。