这无需额外的 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']);
};
结果
使用上面的Gruntfile.js 运行$ grunt(使用您的示例目录结构),将生成一个dist 目录结构如下:
dist
├── keep1
│ └── ...
├── keep2
│ └── ...
└── 3
└── ...