Gruntfile.js详解

使用yeomen新建一个项目,里面会自动帮你创建一个完整项目的全部目录,这里针对新建出来的Gruntfile.js做一下简单说明,用作以后参考使用,由于还是菜鸟,很多东西没有使用过,所以就不做过多的解释,等以后有了一定的理解再做补充

网址

在线API中文版

time-grunt与jit-grunt

  • time-grunt time-grunt地址 完成任务的时间。可以帮助优化建立时间
  • jit-grunt jit-grunt地址 自动加载所需任务

grunt.registerTask

注册 “别名任务” 或 任务函数

grunt.initConfig

任务配置 

如果传入description和taskFunction,每当任务运行时,指定的函数(taskFunction)都会被执行。此外,当执行 grunt –help时,前面指定的描述(description)就会显示出来。特定任务的属性和方法在任务函数内部通过this对象的属性即可访问。如果任务函数返回false表示任务失败。

grunt.task.run

将一个或多个任务放入队列中。 taskList 中的每个任务都会按照其在队列中的顺序,在当前任务执行完毕后立即执行。任务列表可以是一个任务数组或单个任务

config

这里的config可以理解为全局上下文参数设置,后面会用到这里的参数

每个目标的具体设置,需要参考该模板的文档。就cssmin来讲,minify目标的参数具体含义如下:

  • expand:如果设为true,就表示下面文件名的占位符(即*号)都要扩展成具体的文件名。
  • cwd:需要处理的文件(input)所在的目录。
  • src:表示需要处理的文件。如果采用数组形式,数组的每一项就是一个文件名,可以使用通配符。
  • dest:表示处理后的文件名或所在目录。
  • ext:表示处理后的文件后缀名。

除了上面这些参数,还有一些参数也是grunt所有模块通用的。

  • filter:一个返回布尔值的函数,用于过滤文件名。只有返回值为true的文件,才会被grunt处理。
  • dot:是否匹配以点号(.)开头的系统文件。
  • makeBase:如果设置为true,就只匹配文件路径的最后一部分。比如,a?b可以匹配/xyz/123/acb,而不匹配/xyz/acb/123。

关于通配符,含义如下:

  • *:匹配任意数量的字符,不包括/。
  • ?:匹配单个字符,不包括/。
  • **:匹配任意数量的字符,包括/。
  • {}:允许使用逗号分隔的列表,表示“or”(或)关系。
  • !:用于模式的开头,表示只返回不匹配的情况。

watch

watch是一个特殊的任务,它可以在目标文件保存时自动触发一系列任务的运行。在命令行工具中运行grunt watch命令,此时,你修改并保存文件就会触发watch,里面的参数可以看出 

files:[]监控哪些文件,tasks:[]触发后执行哪些任务

BrowserSync

BrowserSync 是一个自动化测试辅助工具,可以帮你在网页文件变更时自动载入新的网页。

clean

grunt-contrib-clean 

清除文件模块

jshinit

grunt-contrib-jshint:检查JavaScript语法

Mocha

Mocha是node.js中最常用的测试框架

sass

将sass转换为css

wiredep

用来根据 bower.json 在指定文件的占位符中注入 JavaScript 或者 CSS 依赖。 

grunt-wiredep

filerev

grunt-filerev

useminPrepare

根据 <%= yeoman.app %>/index.html 中的 usemin 块生成 JS 和 CSS 的压缩配置,并指定输出路径为 <%= yeoman.dist %> 。

usemin

页面中的usemin模块

<!-- build:css(.) styles/vendor.css -->

<!-- bower:css -->

<!-- endbower -->

<!-- endbuild -->

<!-- build:css(.tmp) styles/main.css -->

< link rel = "stylesheet" href = "styles/main.css" >

<!-- endbuild -->

<!-- build:js(.) scripts/vendor.js -->

<!-- bower:js -->

<!-- endbower -->

<!-- endbuild -->

<!-- build:js({.tmp,app}) scripts/scripts.js -->

<!-- endbuild -->

grunt-usemin

imagemin

图像压缩模块 

grunt-contrib-imagemin

svgmin

grunt-svgmin

htmlmin

grunt-htmlmin

copy

用于复制文件与目录 

grunt-contrib-copy

modernizr

grunt-modernizr

concurrent

用于运行并行任务。对于耗时的任务(如 Coffee and Sass)或者运行 多个阻塞任务 (如 nodemon and watch ) 时很有用。 

grunt-concurrent

newer

grunt-newer 配置任务只对新的文件运行任务。 newer 任务不要求特殊的配置,你只需要在任务前加上 newer: 。

附录:grunt.js文件

/*jshint node:true*/

// Generated on 2015-06-30 using
// generator-webapp 0.6.2
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);

// Automatically load required grunt tasks
require('jit-grunt')(grunt, {
useminPrepare: 'grunt-usemin'
});

// Configurable paths
var config = {
app: 'app',
dist: 'dist'
};

// Define the configuration for all the tasks
grunt.initConfig({

// Project settings
config: config,

// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= config.app %>/scripts/{,*/}*.js'],
tasks: ['jshint']
},
jstest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['test:watch']
},
gruntfile: {
files: ['Gruntfile.js']
},
sass: {
files: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['sass:server', 'postcss']
},
styles: {
files: ['<%= config.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'postcss']
}
},

browserSync: {
options: {
notify: false,
background: true
},
livereload: {
options: {
files: [
'<%= config.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= config.app %>/images/{,*/}*',
'<%= config.app %>/scripts/{,*/}*.js'
],
port: 9000,
server: {
baseDir: ['.tmp', config.app],
routes: {
'/bower_components': './bower_components'
}
}
}
},
test: {
options: {
port: 9001,
open: false,
logLevel: 'silent',
host: 'localhost',
server: {
baseDir: ['.tmp', './test', config.app],
routes: {
'/bower_components': './bower_components'
}
}
}
},
dist: {
options: {
background: false,
server: '<%= config.dist %>'
}
}
},

// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= config.dist %>/*',
'!<%= config.dist %>/.git*'
]
}]
},
server: '.tmp'
},

// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'Gruntfile.js',
'<%= config.app %>/scripts/{,*/}*.js',
'!<%= config.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},

// Mocha testing framework configuration options
mocha: {
all: {
options: {
run: true,
urls: ['http://<%= browserSync.test.options.host %>:<%= browserSync.test.options.port %>/index.html']
}
}
},

// Compiles Sass to CSS and generates necessary files if requested
sass: {
options: {
sourceMap: true,
sourceMapEmbed: true,
sourceMapContents: true,
includePaths: ['bower_components']
},
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
},
server: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
}
},

postcss: {
options: {
map: true,
processors: [
// Add vendor prefixed styles
require('autoprefixer-core')({
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
})
]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},

// Automatically inject Bower components into the HTML file
wiredep: {
app: {
src: ['<%= config.app %>/index.html'],
exclude: ['bootstrap.js'],
ignorePath: /^<%= config.app %>\/|\.\.\//
},
sass: {
src: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'],
ignorePath: /(\.\.\/){1,2}bower_components\//
}
},

// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'<%= config.dist %>/images/{,*/}*.*',
'<%= config.dist %>/styles/fonts/{,*/}*.*',
'<%= config.dist %>/*.{ico,png}'
]
}
},

// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
options: {
dest: '<%= config.dist %>'
},
html: '<%= config.app %>/index.html'
},

// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
options: {
assetsDirs: [
'<%= config.dist %>',
'<%= config.dist %>/images',
'<%= config.dist %>/styles'
]
},
html: ['<%= config.dist %>/{,*/}*.html'],
css: ['<%= config.dist %>/styles/{,*/}*.css']
},

// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.{gif,jpeg,jpg,png}',
dest: '<%= config.dist %>/images'
}]
}
},

svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.svg',
dest: '<%= config.dist %>/images'
}]
}
},

htmlmin: {
dist: {
options: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
removeAttributeQuotes: true,
removeCommentsFromCDATA: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
// true would impact styles with attribute selectors
removeRedundantAttributes: false,
useShortDoctype: true
},
files: [{
expand: true,
cwd: '<%= config.dist %>',
src: '{,*/}*.html',
dest: '<%= config.dist %>'
}]
}
},

// By default, your `index.html`'s <!-- Usemin block --> will take care
// of minification. These next options are pre-configured if you do not
// wish to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= config.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= config.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= config.dist %>/scripts/scripts.js': [
// '<%= config.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },

// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= config.app %>',
dest: '<%= config.dist %>',
src: [
'*.{ico,png,txt}',
'images/{,*/}*.webp',
'{,*/}*.html',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
dot: true,
cwd: '.',
src: 'bower_components/bootstrap-sass/assets/fonts/bootstrap/*',
dest: '<%= config.dist %>'
}]
}
},

// Generates a custom Modernizr build that includes only the tests you
// reference in your app
modernizr: {
dist: {
devFile: 'bower_components/modernizr/modernizr.js',
outputFile: '<%= config.dist %>/scripts/vendor/modernizr.js',
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'!<%= config.dist %>/scripts/vendor/*'
]
},
uglify: true
}
},

// Run some tasks in parallel to speed up build process
concurrent: {
server: [
'sass:server'
],
test: [
],
dist: [
'sass',
'imagemin',
'svgmin'
]
}
});


grunt.registerTask('serve', 'start the server and preview your app', function (target) {

if (target === 'dist') {
return grunt.task.run(['build', 'browserSync:dist']);
}

grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'postcss',
'browserSync:livereload',
'watch'
]);
});

grunt.registerTask('server', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run([target ? ('serve:' + target) : 'serve']);
});

grunt.registerTask('test', function (target) {
if (target !== 'watch') {
grunt.task.run([
'clean:server',
'concurrent:test',
'postcss'
]);
}

grunt.task.run([
'browserSync:test',
'mocha'
]);
});

grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'postcss',
'concat',
'cssmin',
'uglify',
'copy:dist',
'modernizr',
'filerev',
'usemin',
'htmlmin'
]);

grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};