[英]Grunt - Can you call grunt-contrib-copy from within a custom registered task and customize the copy on the fly?
我知道我可以在grunt.config中設置一個任務,它將grunt-contrib-copy文件從src復制到dest,並查看Grunt文檔,我知道我可以使用grunt.file.copy復制單個文件。
但是,是否可以在自定義注冊任務中動態創建grunt-contrib-copy任務以適應從bash發送的參數? 我想創建一個新目錄grunt.file.mkdir(“some / path / appfoldername”),然后將文件從另一個目標復制到該文件夾,但在運行自定義任務之前我不會知道文件夾名稱。 所以類似於:
grunt create_app:appfoldername
所以我可以一次復制一個文件,但文件會改變,所以需要grunt-contrib-copy的強大功能,但具有自定義注冊任務的靈活性。
如果我的解釋不夠清楚,我會想象這樣的事情:
grunt.registerTask('createCopy', 'Create a copy', function(folderName) {
var cwd = grunt.template.process("some/path/to/app");
var src = grunt.template.process("some/path/to/src");
var dest = grunt.template.process("some/path/to/dest") + folderName;
grunt.task.run('copy: {
files: {
cwd: cwd,
src: src,
dest: dest
}
}');
}
UPDATE
grunt.registerTask('mkapp', 'Create Application', function(appName) {
// Check appName is not empty or undefined
if(appName !== "" && appName !== undefined) {
// Require node path module, since not a global
var path = require("path");
// Resolve directory path using templates
var relPath = grunt.template.process("<%= root %>/<%= dirs.src %>/application/");
var srcPath = relPath + "default_install";
var destPath = relPath + appName;
// Create new application folder
grunt.file.mkdir(destPath, 0444);
// Return unique array of all file paths which match globbing pattern
var options = { cwd: srcPath, filter: 'isFile' };
var globPattern = "**/*"
grunt.file.expand(options, globPattern).forEach(function(srcPathRelCwd) {
// Copy a source file to a destination path, creating directories if necessary
grunt.file.copy(
path.join(srcPath, srcPathRelCwd),
path.join(destPath, srcPathRelCwd)
);
});
}
});
是。 只需在文件規范上調用grunt.file.expand ,然后遍歷生成的數組,然后根據需要復制它們。
grunt.file.expand(specs).forEach(function(src) {
grunt.file.copy(src, dest);
});
如果您希望跨平台工作,可以使用Node的路徑API來創建具有正確路徑分隔符的文件路徑等。
grunt.file.expand(options, globPattern).forEach(function(srcPathRelCwd) {
// Copy a source file to a destination path, creating directories if necessary
grunt.file.copy(
path.join(srcPath, srcPathRelCwd),
path.join(destPath, srcPathRelCwd)
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.