Grunt-Contrib-Copy,如何在不覆盖 dest 文件夹中的现有文件/文件夹的情况下复制保持相同文件夹结构的目录内容?

约翰·多伊

源结构```文件夹

|----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 已经存在,因此不应触及它们,其他文件/文件夹应该创建,所以我想递归检查“文件夹”内部是否存在文件,如果不存在则复制它。我一直在使用以下过滤器来不覆盖单个文件过滤器: function (filepath) { return !(grunt.file.exists('dest')); 但是 ' 文件夹包含多个子目录和文件,因此无法为每个文件写入。请帮助编写可以执行此操作的自定义 grunt 任务。

罗伯克

这可以通过filtergrunt-contrib-copy目标函数中添加自定义逻辑来执行以下操作来实现:

  1. 利用 nodejs路径模块来帮助确定结果路径是什么。
  2. 使用grunt.file.exists确定文件是否已存在于其目标路径中

以下要点演示了如何跨平台实现您的需求:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章