@asgoth的answer肯定会工作,但想通了几个其他的选项,以及为‘注入’(或删除)代码在构建过程中。
如在example build.js file中所述,我们可以使用构建pragmas
在构建过程中包含/排除代码片段。
//Specify build pragmas. If the source files contain comments like so:
//>>excludeStart("fooExclude", pragmas.fooExclude);
//>>excludeEnd("fooExclude");
//Then the comments that start with //>> are the build pragmas.
//excludeStart/excludeEnd and includeStart/includeEnd work, and the
//the pragmas value to the includeStart or excludeStart lines
//is evaluated to see if the code between the Start and End pragma
//lines should be included or excluded. If you have a choice to use
//"has" code or pragmas, use "has" code instead. Pragmas are harder
//to read, but they can be a bit more flexible on code removal vs.
//has-based code, which must follow JavaScript language rules.
//Pragmas also remove code in non-minified source, where has branch
//trimming is only done if the code is minified via UglifyJS or
//Closure Compiler.
pragmas: {
fooExclude: true
},
//Same as "pragmas", but only applied once during the file save phase
//of an optimization. "pragmas" are applied both during the dependency
//mapping and file saving phases on an optimization. Some pragmas
//should not be processed during the dependency mapping phase of an
//operation, such as the pragma in the CoffeeScript loader plugin,
//which wants the CoffeeScript compiler during the dependency mapping
//phase, but once files are saved as plain JavaScript, the CoffeeScript
//compiler is no longer needed. In that case, pragmasOnSave would be used
//to exclude the compiler code during the save phase.
pragmasOnSave: {
//Just an example
excludeCoffeeScript: true
},
我可以在jquery.mobile
code行动,这可能是从学习AMD
和requirejs
的好地方看到这一点。
这里是我工作:
AppLogger.js:
/* global console: false */
define(function() {
var debugEnabled = false;
//>>excludeStart('appBuildExclude', pragmas.appBuildExclude);
debugEnabled = true;
//>>excludeEnd('appBuildExclude');
return {
log:function (message) {
if (debugEnabled && console) {
console.log('APP DEBUG: ' + message);
}
}
};
});
Gruntfile.js:
requirejs:{
compile:{
options:{
baseUrl:"js/",
mainConfigFile:"js/main.js",
name:'main',
out:'js/main.min.js',
pragmas:{ appBuildExclude:true }
}
}
}
利用这种配置为requirejs
我Gruntfile
,的编译内部分从编译/构建的文件中剥离了和excludeEnd
。
我还在学习requirejs
,所以没有人声称这是这类事情的最佳实践,但这肯定对我有用。
感谢您的回答。我所寻找的东西稍有不同,我试图通过对问题的更新来澄清它。 – 2013-03-04 12:51:52
编辑我的答案。看看是否有帮助。 – asgoth 2013-03-04 13:31:42
这肯定会起作用,但想出了另一个从[r.js示例构建文件]构建'pragmas'的选项(https://github.com/jrburke/r.js/blob/master/build/example.build .js文件)。这显然是'jquery.mobile' [也使用](https://github.com/jquery/jquery-mobile/blob/master/js/jquery.mobile.events.js)。我已经接受了你的答案,但是会为我的工作增加另一个我自己的答案。谢谢! – 2013-03-04 17:23:42