【问题标题】:Grunt Concat many files in many folders while maintaining folder structureGrunt Concat 许多文件夹中的许多文件,同时保持文件夹结构
【发布时间】:2015-10-19 17:31:01
【问题描述】:
我在我的项目中使用 Grunt concat。我想在文件夹级别合并文件。
例如
js >
parent >
child1 >
a.js
b.js
c.js
child2 >
a.js
b.js
进入:
js >
parent >
child1 >
child1combined.js
child2 >
child2combined.js
有没有办法做到这一点,而无需在自己的连续行中专门添加每个“孩子”?
【问题讨论】:
标签:
gruntjs
grunt-contrib-concat
【解决方案1】:
我最终做了我在this post 中找到的以下内容。
grunt.registerTask("taskName", "Task Description", function() {
// get all module directories
grunt.file.expand("src/js/parent/*").forEach(function (dir) {
// get the module name from the directory name
var dirName = dir.substr(dir.lastIndexOf('/')+1);
// get the current concat object from initConfig
var concat = grunt.config.get('concat') || {};
// create a subtask for each module, find all src files
// and combine into a single js file per module
concat[dirName] = {
src: [dir + '/**/*.js'],
dest: 'build/js/parent/' + dirName + '/combined.js'
};
// add module subtasks to the concat task in initConfig
grunt.config.set('concat', concat);
});
});
然后只需从您的 registerTask 中调用 taskName。
【解决方案2】:
在你的 concat 任务中使用globbing patterns。引用链接的文档:
单独指定所有源文件路径通常是不切实际的,
所以 Grunt 支持文件名扩展(也称为 globbing)。
【解决方案3】:
我知道这个话题很老,但我想分享我的解决方案,因为我在网络上找不到按预期工作的简单解决方案。
concat: {
files: [
{
expand: true,
src: ["**/*.js"],
dest: "dest/js",
cwd: "src/js",
rename: function(dst, src) {
const srcParts = String(src).split("/");
let dstPath = "";
let dstName = srcParts[0].split(".")[0];
if (srcParts.length > 1) {
dstName = srcParts[srcParts.length - 2];
dstPath =
srcParts
.slice(0, srcParts.length - 1)
.join("/") + "/";
}
return `${dst}/${dstPath + dstName}.js`;
}
}
]
}
我希望这对某人有帮助:)