Grunt学习笔记【5】---- expand使用方法
本文主要讲expand使用方法。
当你希望处理大量的单个文件时,这里有一些附加的属性可以用来动态的构建一个文件列表。这些属性都可以用于 Compact 和 Files Array 文件映射格式。
expand
设置为true
将启用下面的选项:
-
cwd
所有src
指定的匹配都将相对于此处指定的路径(但不包括此路径) 。 -
src
相对于cwd
路径的匹配模式。 -
dest
目标文件路径前缀。 -
ext
对于生成的dest
路径中所有实际存在文件,均使用这个属性值替换扩展名。 -
extDot
用于指定标记扩展名的英文点号的所在位置。可以赋值'first'
(扩展名从文件名中的第一个英文点号开始) 或'last'
(扩展名从最后一个英文点号开始),默认值为'first'
[添加于 0.4.3 版本] -
flatten
从生成的dest
路径中移除所有的路径部分。 -
rename
嵌入自定义函数,返回包含新目标和文件名的字符串。为每个匹配的src
文件调用此函数(在扩展名重命名和flatten后)。更多信息
在下面的例子中,uglify
任务中的static_mappings
和dynamic_mappings
两个目标具有相同的src-dest
文件映射列表, 这是因为任务运行时Grunt会自动展开dynamic_mappings
文件对象为4个单独的静态src-dest
文件映射--假设这4个文件能够找到。
可以指定任意静态src-dest
和动态的src-dest
文件映射相互结合。
1 grunt.initConfig({ 2 uglify: { 3 static_mappings: { 4 // Because these src-dest file mappings are manually specified, every 5 // time a new file is added or removed, the Gruntfile has to be updated. 6 files: [ 7 {src: 'lib/a.js', dest: 'build/a.min.js'}, 8 {src: 'lib/b.js', dest: 'build/b.min.js'}, 9 {src: 'lib/subdir/c.js', dest: 'build/subdir/c.min.js'}, 10 {src: 'lib/subdir/d.js', dest: 'build/subdir/d.min.js'}, 11 ], 12 }, 13 dynamic_mappings: { 14 // Grunt will search for "**/*.js" under "lib/" when the "uglify" task 15 // runs and build the appropriate src-dest file mappings then, so you 16 // don't need to update the Gruntfile when files are added or removed. 17 files: [ 18 { 19 expand: true, // Enable dynamic expansion. 20 cwd: 'lib/', // Src matches are relative to this path. 21 src: ['**/*.js'], // Actual pattern(s) to match. 22 dest: 'build/', // Destination path prefix. 23 ext: '.min.js', // Dest filepaths will have this extension. 24 extDot: 'first' // Extensions in filenames begin after the first dot 25 }, 26 ], 27 }, 28 }, 29 });
rename属性详细说明:
rename函数必须返回一个有效的命名字符串。
参数可以是dest和src。
在以下示例中,文件从dev
文件夹复制到dist
文件夹,并重命名为删除了“beta”。
1 grunt.initConfig({ 2 copy: { 3 production: { 4 files: [{ 5 expand: true, 6 cwd: 'dev/', 7 src: ['*'], 8 dest: 'dist/', 9 rename: function (dest, src) { // The `dest` and `src` values can be passed into the function 10 return dest + src.replace('beta',''); // The `src` is being renamed; the `dest` remains the same 11 } 12 }] 13 } 14 } 15 });
参考资料&内容来源:
grunt官网:https://www.gruntjs.net/configuring-tasks#files-array-format