Grunt - read json object from file

家住魔仙堡 提交于 2019-12-09 08:41:45

问题


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?


回答1:


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! :)



来源:https://stackoverflow.com/questions/24934315/grunt-read-json-object-from-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!