grunt-contrib-concat可用于合并任意文件(css\js\txt等)
安装插件:npm install grunt-contrib-concat --save-dev
参数:
separator
参数类型:string
默认值:grunt.util.linefeed
可用一切string类型的字符分割,如“;”
banner
参数类型:string
默认值:""(空值)
在输出的文档的头部添加,一般做说明和注释用。参数如:‘/*! <%= pkg.name %> <%=
grunt.template.today("yyyy-mm-dd") %> */\n‘
footer
与banner相似,但其在输出的文档的底部添加
stripBanners
参数类型:Boolean、Object
默认值:false
为true,去除代码中的块注释。
Object:
block:如果为true,去除所有的块注释
line:如果为true,去除任何连续的//领导的行注释
process
参数类型:Boolean、object、funtion
默认值:false
处理的源文件在连接之前,作为模板或一个自定义函数。
false - 没有要处理的
true - 处理的源文件使用grunt.template.process的默认值
object - 处理的源文件使用grunt.template.process中指定选项
function(src,filepath) - 处理的源文件每个文件都使用被定义的函数处理,返回值将作为源文件使用
实例如下:
1.合并src下的js到bulid目录,合并后文件名为built.js:
concat:{ options: { //文件内容分隔符 separator: ";", stripBanner: true, //在文件头部添加 banner: ‘/*! <%= pkg.name %> - v<%= pkg.version %> - ‘ + ‘<%= grunt.template.today("yyyy-mm-dd") %> */‘, //自定义进程函数,比如你需要在合并文件前,对文件名进行处理等 process: function(src, filepath) { return ‘// Source: ‘ + filepath + ‘\n‘ + src.replace(/(^|\n)[ \t]*(‘use strict‘|"use strict");?\s*/g, ‘$1‘); } }, dist: { src: [‘src/*.js‘], dest: ‘build/built.js‘ } }
2.合并多个目标文件
concat: { options: { separator: ";" }, basic: { src: [‘txt/*.txt‘], dest: ‘txt/common.txt‘ }, extras: { src:[‘src/*.js‘], dest: "js/common.min.js" } }
或
concat: { options: { separator: ";" }, basic: { files: { ‘txt/common.txt‘ : [‘txt/*.txt‘], ‘js/common.min.js‘ : [‘src/*.js‘] } } }
3.动态的文件名
grunt.initConfig({ pkg: grunt.file.readJSON(‘package.json‘), dirs: { src: ‘src‘ }, concat: { options: { separator: ";" }, extras: { src:[‘<%= dirs.src %>/*.js‘], dest: "js/<%= pkg.name %>.min.js" } } });
4.无效或丢失的文件的警告,设置nonull为true
concat: { options: { separator: ";" }, extras: { src:[‘<%= dirs.src %>/*.js‘], dest: "js/<%= pkg.name %>.min.js", nonull: true } }
当然,除了在grunt.initConfig中配置concat,还需要在Gruntfile.js中添加下面两段代码,那么,这个插件就算配写完成了
//加载指定插件任务
grunt.loadNpmTasks(‘grunt-contrib-concat‘);
//注册插件任务
grunt.registerTask(‘default‘,[‘concat]);
原文:http://www.cnblogs.com/cyj7/p/4844015.html