The following is a webpack loader for Phaser asset files. The way this is supposed to work is that it looks at the json string, and finds all of values with "url" keys in the json object, and transforms that value to a function call with that value as the parameter. I need to assume any level of nesting of the json values.
module.exports = function(source){
this.cacheable(); //comment this line out to run standalone outside webpack loader context
var s = source;
var re = /"url":\s*\".*,/g;
var m;
do {
m = re.exec(source);
if (!!m) {
var path = m[0].split(':')[1].trim().slice(0, -1);
s = s.replace(path, 'require(' + path + ')');
}
} while (m);
return s;
}
For example, the source could be the following as the parameter to the function (as a string)
{
"level1": [{
"type": "image",
"key": "starwars",
"url": "assets/pics/unknown-the_starwars_pic.png",
"overwrite": false
},{
"type": "image",
"key": "spaceship",
"url": "assets/pics/spaceship.png",
"overwrite": false
}
],
"level2": [{
"type": "image",
"key": "spaceship",
"url": "assets/pics/spaceship.png",
"overwrite": false
}
]
}
and the return value would be a string of the following
{
"level1": [{
"type": "image",
"key": "starwars",
"url": require("assets/pics/unknown-the_starwars_pic.png"),
"overwrite": false
},{
"type": "image",
"key": "spaceship",
"url": require("assets/pics/spaceship.png"),
"overwrite": false
}
],
"level2": [{
"type": "image",
"key": "spaceship",
"url": require("assets/pics/spaceship.png"),
"overwrite": false
}
]
}
How might I implement this in a more clear way that accounts for any nesting of the json objects?