三、利用Grunt实现项目自动化打包
Grunt是一款基于node的javascript任务管理器工具。我们的项目使用Grunt实现项目自动化打包,以及后续的持续集成。Grunt如何使用,本文不详细介绍(其实是不会-_-!),详见《【grunt整合版】30分钟学会使用grunt打包前端代码》。
1、打包思路
项目从开发态到发布态,需要做哪些事情?一、代码检查,包括代码风格检查、js静态代码检查、单元测试、代码静态分析。二、文件预处理:包括sass转css、seajs模块转换、文件变量宏替换。三、文件拷贝、压缩、合并。所以处理流程也很简单。如下图所示:
2、代码风格检查
Grunt中代码风格检查插件很多,我们的项目采用的是jscs-dev/grunt-jscs。另外,为了生成代码风格检查报告,还需要aj-dev/jscs-html-reporter报表插件。配置参数如下:
jscs: {
src: ['script/module/**/*.js', '!script/module/**/tpl/*.js'],
options: {
config: '.jscsrc',
reporter: 'node_modules/jscs-html-reporter/jscs-html-reporter.js',
reporterOutput: 'report/jscs/index.html'
}
},
其中,.jscsrc是代码风格规则文件。参考配置如下:
{
"disallowSpacesInNamedFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInAnonymousFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInFunctionDeclaration": {
"beforeOpeningRoundBrace": true
},
"disallowEmptyBlocks": true,
"disallowSpacesInsideArrayBrackets": true,
"disallowSpacesInsideParentheses": true,
"disallowQuotedKeysInObjects": true,
"disallowSpaceAfterObjectKeys": true,
"disallowSpaceAfterPrefixUnaryOperators": true,
"disallowSpaceBeforePostfixUnaryOperators": true,
"disallowSpaceBeforeBinaryOperators": [
","
],
"disallowMixedSpacesAndTabs": true,
"disallowTrailingWhitespace": true,
"disallowTrailingComma": true,
"disallowYodaConditions": true,
"disallowKeywords": [ "with" ],
"disallowMultipleLineBreaks": true,
"requireSpaceBeforeBlockStatements": tr