grunt复制已排序目录的一部分

时间:2017-08-24 06:58:59

标签: gruntjs grunt-contrib-copy

我有一个如下目录结构:

dist/
static/
static/keep1
static/keep2
static/versions/1
static/versions/2
static/versions/3

我想将static中的所有内容复制到dist,但versions目录除外。我想对目录进行排序并采用最新版本(例如版本3)。

如果我只是做{expand: true, cwd:'static', src: '**', dest: 'dist/', dot: 'true'},我会变老,不必要的版本会膨胀我的dist/目录

有没有办法以编程方式选择最新版本,所以每次更新static/versions/时我都不必手动更新我的gruntfile配置?

我认为我可能会node-globminimatch为我工作,或者我可以使用grunt-executegrunt-run(两者都可能获得)丑陋)。我希望有一种方法可以用副本来做。

1 个答案:

答案 0 :(得分:1)

这可以在没有其他 grunt 插件的情况下实现。但是,必须以编程方式查找存储在./versions/目录中的最新版本,并且必须在运行copy任务之前计算此版本。 grunt-contrib-copy没有内置功能来确定。

确定最新版本目录后,只需在copy任务中使用几个Targets

以下要点说明了如何实现这一目标:

注意:此解决方案假定最新版本是编号最高的目录,并且不会以任何方式通过创建或修改日期确定。

<强> Gruntfile,JS

module.exports = function(grunt) {

  'use strict';

  // Additional built-in node module.
  var stats = require('fs').lstatSync;

  /**
   * Find the most recent version. Loops over all paths one level deep in the
   * `static/versions/` directory to obtain the highest numbered directory.
   * The highest numbered directory is assumed to be the most recent version.
   */
  var latestVersion = grunt.file.expand('static/versions/*')

    // 1. Include only directories from the 'static/versions/' 
    //    directory that are named with numbers only.
    .filter(function (_path) {
      return stats(_path).isDirectory() && /^\d+$/.test(_path.split('/')[2]);
    })

    // 2. Return all the numbered directory names.
    .map(function (dirPath) { return dirPath.split('/')[2] })

    // 3. Sort numbers in ascending order.
    .sort(function (a, b) { return a - b; })

    // 4. Reverse array order and return highest number.
    .reverse()[0];


  grunt.initConfig({
    copy: {

      // First target copies everything from `static`
      // to `dist` excluding the `versions` directory.
      allExludingVersions:{
        files:[{
          expand: true,
          dot: true,
          cwd: 'static/',
          src: ['**/*', '!versions/**'],
          dest: 'dist/'
        }]
      },

      // Second target copies only the sub directory with the
      // highest number name from `static/versions` to `dist`.
      latestVersion: {
        files: [{
          expand: true,
          dot: true,
          cwd: 'static/versions/',
          src: latestVersion + '/**/*',
          dest: 'dist/'
       }]
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.registerTask('default', ['copy']);
};

<强>结果

使用上面的$ grunt(使用您的示例目录结构)运行Gruntfile.js将导致dist目录的结构如下:

dist
├── keep1
│   └── ...
├── keep2
│   └── ...
└── 3
    └── ...