Grunt动态变量问题(未定义)
Grunt dynamic variable issue (undefined)
我在我的grunt文件中有一个作用域问题,我需要一个计数器变量去每次新的时间grunt.task.run完成,在分钟我只能使用asp_files[0]每次,然而我的愿望是通过每个asp/html文件存储在一个数组中,然后执行我的各种grunt任务在该文件(已经有这个工作的模板代码,我只是不能让我的索引变量改变)
下面是我调用grunt模块的方式
for (var x = 0; x < asp_files.length; x++){
grunt.task.run ( [
//'clean:build',
'copy:build',
'replace:gather',
'uglify:js',
]);
}
这是我的复制模块
copy: {
build: {
files: [
{
dest: 'build/copied',
expand: true,
src: 'html/'+asp_files['<%= counterVar %>']
}
]
}
},
counter应该在这里递增
replace: {
gather: {
files: [
{
dest: 'build',
expand: true,
// This doesn't work, however asp_files[0] works fine, as does asp_files[globalCount] however it never actually increments past 0..
src: 'html/'+asp_files['<%= counterVar %>']
}
],
options: {
patterns: [
{
//Grab the <!--build-js-start--> and <!--build-js-end--> comments and everything in-between
match: /'<'!'-'-build'-js'-start['s'S]*build'-js'-end'-'-'>/,
replacement: function ( matchedString ) {
js_filename = file_names[globalCount];
grunt.config( 'counter', globalCount );
globalCount++;
var count = grunt.config('counter');
// This prints out the count correctly...
console.log("The config counter value is: "+count);
我已经尝试了许多不同的方法,试图得到一个计数器或任何类型的变量通过每次构建改变,但无济于事
我做错了什么让我的counterVar永远不会改变我的replace:gather模块之外?(这里有完整的工作源代码,如果需要:http://pastebin.com/F1cdSeB4)
谢谢
Grunt的方法是从另一个角度看问题:列出所有文件,并要求每个任务处理所有文件(而不是在一个文件上运行所有任务):
var aspFiles = ['html/file1.asp', 'html/file2.asp'];
//...
grunt.initConfig({
copy: {
build: {
files: [{
dest: 'build/copied',
expand: true,
src: aspFiles
}]
}
},
replace: {
gather: {
files: [{
dest: 'build',
expand: true,
src: aspFiles
}]
}
}
});
您的问题是grunt.task.run
实际上并不运行任务,它只是将其添加到任务堆栈中,以便在当前任务完成后运行。基本上你的计数器变量被设置为它的最后一个值,同样的任务运行N次。更全局地说,永远不要重用任务外部的javascript变量(如jsResources) -将其转换为唯一的不可变变量(如jsResources的文件名数组- jsResources[path] =[…])。
所以要得到你想要的,你需要在循环中创建N个不同的目标,并将它们添加到运行堆栈中——例如:
for (var x = 0; x < asp_files.length; x++){
// we create targets copy:build0, copy:build1, etc.
var target = 'copy:build'+x;
grunt.config(target, {
files: [{
dest: 'build/copied',
expand: true,
src: 'html/'+asp_files[x]
}]
});
// then queue them for running
grunt.task.run ([
// copy:build0
target
]);
}
您需要扩展以对所有您想以这种方式运行的任务执行相同的操作(丑陋)
相关文章:
- 如何消除代码中的未定义和其他问题
- 组件生命周期问题/无法处理未定义的问题
- JavaScript/jQuery JSON数组问题-值为未定义
- 使用Breeze脱机数据时出现未定义的问题不是函数
- 如何使用警报进行调试来解决(未定义的)时间问题
- SJCL的问题“;无法读取属性'替换'“未定义”;
- JSON JavaScript 未定义的变量问题
- 创建可在任何地方使用的 JS 函数?范围和功能“未定义”的问题
- 将 AJAX 传递给 PHP 时遇到问题,而是未定义
- 尝试添加到根父节点时出现 KendoUI 未定义节点问题
- 榆树早午餐编译问题:“拆分”未定义
- JavaScript,jquery中未定义的VAR的问题.如何
- JS Revearing Pattern事件未定义问题
- 未捕获引用错误:未定义问题
- Javascript未定义问题
- IE8中控制台未定义问题
- JavaScript全局变量未定义问题
- 对象未定义问题
- 使用Google' Javascript API的未定义问题
- JS对象未定义问题