更新时间:2023-09-27 20:40:22
我做了类似于jakerella建议的事情,决定使用通配模式(如Florian F.所建议的)。我添加了一个新的Grunt任务:
var fs = require(fs);
grunt.registerTask(filelist,列出目录中的文件为JSON字符串到文件,function(){
var list,
done = this.async(),
output = grunt.config(filelist.images.output),
outputVariable = grunt.config(filelist.images.outputVariable),
patterns = grunt.config(filelist.images .patterns),
headerComment ='/ *这个文件是使用Grunt任务`filelist`自动生成的。* / \';
list = grunt.file.expand(模式);
fs.writeFile(output,
headerComment + outputVariable +'='+ JSON.stringify(list)+';',
function(err){
if(err){
throw err;
}
grunt.log.writeln(保存到+ output的+ list.length +文件列表;
done();
});
});
我将它添加到我的配置中:
filelist:{
images:{
output:app / generated / image-list.js,
outputVariable:game.imageList ,
patterns:[app / resources / img / ** / *],
},
},
通过这种方式,我可以将数据包含在< script>
标记中,就像任何其他JS一样。谢谢你们,伙计们! :)
I'm writing an online game in HTML5. One of the files contains a list of resources which are all in resources/img/
folder. Now I'd like this list to be automatically generated based on contents of this folder, rather than having to update it manually every time I add a new image. I'm pretty sure that Grunt can do this, but I don't know how to configure it properly. What should I do to have Grunt generate something like this?
resources = ['a.jpg', 'b.png', 'subfolder/c.png'];
I did something similar to what jakerella suggested, but I decided to use globbing patterns (as suggested by Florian F.). I added a new Grunt task:
var fs = require("fs");
grunt.registerTask("filelist", "Lists files in a directory as JSON string to file", function() {
var list,
done = this.async(),
output = grunt.config("filelist.images.output"),
outputVariable = grunt.config("filelist.images.outputVariable"),
patterns = grunt.config("filelist.images.patterns"),
headerComment = '/* This file was auto-generated using Grunt task `filelist`. */\n';
list = grunt.file.expand(patterns);
fs.writeFile(output,
headerComment + outputVariable + ' = ' + JSON.stringify(list) + ';',
function (err) {
if (err) {
throw err;
}
grunt.log.writeln("List of " + list.length + " files saved to " + output);
done();
});
});
And I added this to my config:
filelist: {
images: {
output: "app/generated/image-list.js",
outputVariable: "game.imageList",
patterns: ["app/resources/img/**/*"],
},
},
This way I can include the data with a <script>
tag, just like any other JS. Thank you both, guys! :)