Grunt – 你可以从一个自定义的注册任务中调用grunt-contrib-copy,并自定义副本吗?

我知道我可以在grunt.config中设置一个任务grunt-contrib-copy从src到dest的文件,并通过Grunt文档查看我知道我可以使用grunt.file.copy复制单个文件。

但是,是否可以在自定义注册任务中dynamic创buildgrunt-contrib-copy任务,以容纳从bash发送的参数? 我想创build一个新目录grunt.file.mkdir(“some / path / appfoldername”),然后将文件从另一个目标文件复制到该文件夹​​,但直到运行自定义任务后,我才知道文件夹名称。 所以像这样:

grunt create_app:appfoldername 

所以我可以一次复制一个文件,但是文件会改变,所以需要grunt-contrib-copy的强大function,但是可以自定义注册任务的灵活性。

如果我的解释不够清楚,我想像这样:

 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的pathAPI来使用正确的path分隔符等来创build文件path。

 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) ); });