Grunt - 从文件读取json对象 [英] Grunt - read json object from file
问题描述
我想使用 grunt-hash 插件重命名我的js文件。
这个插件创建一个包含重命名文件映射的新文件:
hash:{
options:{
mapping:'examples / assets.json',//映射文件,以便您的服务器可以提供正确的文件
现在我需要通过替换所有用法(将'index.js'重命名为'index- {hash} .js')来修复这些文件的链接,所以我想使用 grunt-text-replace 插件。
根据文档,我需要cofigure替换:
替换:{
示例:{
替换:[{
from:'Red',// string replacement'
to:'Blue'
}]
}
}
如何读取json映射文件以获取每个文件的{hash}值并提供它们以替换任务?
grunt.file.readJSON('your-file.json')
可能就是您要找的东西。
我已经设置了一个小测试。我有一个简单的JSON文件'mapping.json',它包含以下JSON对象:
{
mapping :[
{file:foo.txt},
{file:bar.txt}
]
}
在我的Gruntfile.js中,我写了下面这个简单的测试任务,它读取'mapping'数组中的第一个对象:
$ b $ pre $ g $ c $ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $% grunt.file.readJSON('mapping.json');
grunt.log.write(mapping.mapping [0] [file])。ok();
});
当调用Grunt任务时,控制台输出如下:
$ grunt doStuff
运行doStuff任务
foo.txtOK
完成,没有错误。
我希望这有助于您! :)
I want to use grunt-hash plugin for renaming my js files. This plugin create a new file containing map of renamed files:
hash: {
options: {
mapping: 'examples/assets.json', //mapping file so your server can serve the right files
Now I need to fix links to this files by replacing all usages (rename 'index.js' to 'index-{hash}.js') so I want to use grunt-text-replace plugin. According to documentation I need to cofigure replacements:
replace: {
example: {
replacements: [{
from: 'Red', // string replacement
to: 'Blue'
}]
}
}
How could I read json mapping file to get {hash} values for each file and provide them to replace task?
grunt.file.readJSON('your-file.json')
is probably what you are looking for.
I've set up a little test. I have a simple JSON file 'mapping.json', which contains the following JSON object:
{
"mapping": [
{"file": "foo.txt"},
{"file": "bar.txt"}
]
}
In my Gruntfile.js I've written the following simple test task, which reads the first object in the 'mapping'-array:
grunt.registerTask('doStuff', 'do some stuff.', function() {
mapping = grunt.file.readJSON('mapping.json');
grunt.log.write(mapping.mapping[0]["file"]).ok();
});
When invoking the Grunt task, the console output will be as follows:
$ grunt doStuff
Running "doStuff" task
foo.txtOK
Done, without errors.
I hope this helps! :)
这篇关于Grunt - 从文件读取json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!