【问题标题】:Grunt-Contrib-Copy, how to copy contents of a directory keeping the same folder structure without overwriting existing files/folders in dest folder?Grunt-Contrib-Copy,如何复制保持相同文件夹结构的目录内容而不覆盖dest文件夹中的现有文件/文件夹?
【发布时间】:2018-05-04 06:18:35
【问题描述】:

源结构 ``` 文件夹

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

【问题讨论】:

    标签: javascript gruntjs grunt-contrib-copy


    【解决方案1】:

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

    1. 利用 nodejs path 模块来帮助确定生成的路径。
    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' ]);
    };
    

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多