来源结构 ``` 夹
|----Sub-Folder-1
| |-a.js
| |-b.js
|----Sub-Folder-2
| |-c.js
|-d.js
|-e.js
```
运行复制任务之前的目标结构 ``` 夹
|----Sub-Folder-1
| |-a.js
|-e.js
```
我需要目标文件夹与src文件夹完全相同,但我不想覆盖现有文件,例如上面例子中的a.js和e.js已经存在,所以不应该触及它们,其他应创建文件/文件夹,因此如果文件存在与否,我想以递归方式检查“文件夹”内部,如果文件不存在则复制它。我一直在使用以下过滤器来覆盖单个文件 filter:function(filepath){return!(grunt.file.exists('dest'));但''文件夹包含多个子目录和文件,因此不可能为每个文件编写。请帮助编写可以执行此操作的自定义grunt任务。
答案 0 :(得分:1)
这可以通过在grunt-contrib-copy目标的filter
函数中添加自定义逻辑来实现,以执行以下操作:
以下要点演示了如何跨平台实现您的需求:
<强> Gruntfile.js 强>
module.exports = function (grunt) {
'use strict';
var path = require('path'); // Load additional built-in node module.
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.initConfig({
copy: {
non_existing: {
expand: true,
cwd: 'src/', // <-- Define as necessary.
src: [ '**/*.js' ],
dest: 'dist/', // <-- Define as necessary.
// Copy file only when it does not exist.
filter: function (filePath) {
// For cross-platform. When run on Windows any forward slash(s)
// defined in the `cwd` config path are replaced with backslash(s).
var srcDir = path.normalize(grunt.config('copy.non_existing.cwd'));
// Combine the `dest` config path value with the
// `filepath` value excluding the cwd` config path part.
var destPath = path.join(
grunt.config('copy.non_existing.dest'),
filePath.replace(srcDir, '')
);
// Returns false when the file exists.
return !(grunt.file.exists(destPath));
}
}
}
});
grunt.registerTask('default', [ 'copy:non_existing' ]);
};