你可以考虑:
- 从
package.json 动态获取版本,同时从您的位置复制项目,使用options.process 函数。
- 将其作为属性存储在最初为空的对象中。
- 然后稍后在另一个
copy 任务目标中引用它。
以下要点似乎有效:
Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
// A 'version' property key and value (obtained via a copied package.json)
// will be dynamically added to this empty object and referenced later.
obtainedFromPackage: {},
copy: {
options: {
// Avoid binaries getting corrupted. For more info see:
// https://github.com/gruntjs/grunt-contrib-copy/issues/213
noProcess: ['**/*.{png,gif,jpg,ico,pdf}']
},
initial: {
files: [{
expand: true,
cwd: 'src/',
src: '**/*',
dest: './copiedItems/'
}],
options: {
// Use/abuse the 'options.process' function to obtain the 'version'
// value from the copied 'package.json'. This value is added to a
// 'version' property in the empty 'obtainedFromPackage' object.
process: function(content, srcpath) {
if (srcpath.indexOf('package.json') !== -1) {
var pkgVersion = grunt.file.readJSON(srcpath).version;
grunt.config('obtainedFromPackage.version', pkgVersion);
}
return content //Ensure original file content is not deleted.
}
}
},
copyDocs : {
files: [{
expand: true,
// Change directory to version obtained in previous copy task.
cwd: './networkPath/<%= obtainedFromPackage.version %>/',
src: 'docs/**',
dest: './copiedItems/'
}]
}
}
});
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.registerTask('copyFiles', [
'copy:initial',
'copy:copyDocs'
]);
};
注意:这显然需要适应您的要求。
特别是路径引用!
目录设置
Gruntfile.js 中的示例要点假设一个虚构的项目目录设置如下:
project
├── Gruntfile.js (the one shown above)
├── networkPath
│ ├── 0.0.0
│ │ └── docs
│ │ ├── baz
│ │ │ └── baz.html
│ │ └── index.html
│ └── 1.1.1
│ └── docs
│ ├── foo
│ │ └── foo.html
│ └── index.html
├─── node_modules
│ └── ...
├─── package.json
└─── src
├─── a
│ └─── b.js
└─── package.json
...其中package.json 的version 属性(位于src 文件夹中)设置为:
"version": "1.1.1",
...而名为 networkPath 的文件夹是我假设存储您的文档的位置。
运行任务
通过 CLI 执行以下命令:
$ grunt copyFiles
结果输出
运行任务会在根project 目录中创建一个新文件夹,如下所示:
project
├── copiedItems
│ ├── a
│ │ └── b.js
│ ├── docs
│ │ ├── foo
│ │ │ └── foo.html
│ │ └── index.html
│ └─── package.json
├─ ...
└─ ...
注意事项:
-
src 文件夹中的所有项目(上面的 目录设置 部分中显示的项目)都被复制到新创建的名为 copiedItems。
-
docs 文件夹及其内容来自名为 1.1.1 的文件夹(上面的目录设置部分中显示的那个)被复制到新创建的名为 copiedItems 的文件夹中。正在复制此特定文件夹,因为其父目录名称与正在复制的 package.json 的 version 属性匹配。
我希望这会有所帮助!
更新:
在将一些二进制图像添加到src 文件夹后,我发现生成的复制图像已损坏。请参阅此issue 登录grunt-contrib-copy 存储库以获取更多信息。
上面的Gruntfile.js 现在利用options.noprocess 作为copy 任务中的全局变量作为保护措施。
现在已成功复制图像文件 :)