Search code examples
azure-devopsrequirejsazure-devops-extensions

How can i read external json file in Azure-devops-extension development?


I am trying to read json file inside "index.html" file of the project, since for azure devops extension we already have require.js library, hence wanted to use the same capability of it to import "config.json" file inside "index.html" file.

basic file structure:
|-index.html
|-static  |-icon.png
|    |-config.json
|-vss-extension.json

my index.html file look somewhat like this :

init block

VSS.init({
        explicitNotifyLoaded: true,
        usePlatformScripts: true,
        setupModuleLoader: true,
        moduleLoaderConfig: {
          paths: {
            "Static": "static"
          }
        }
});

require block

VSS.require(
        ["TFS/WorkItemTracking/Services", "Static/config"],
        function (_WorkItemServices, ConfigJson) {

        VSS.ready(function(){
            VSS.register(VSS.getContribution().id, function () {
              return {
                // Called when the active work item is modified
                onFieldChanged: function (args) {
                  console.log(
                    "inside onfield : " +
                      JSON.stringify(ConfigJson)
                  );
                }
                ....
              };
            });

            VSS.notifyLoadSucceeded();
        })
});

My vss-extension.json file :

File block

"files": [
    {
      "path": "static/config.json",
      "addressable": true,
      "contentType": "application/json"
    },
    ....
  ]

I am always getting require.js Script error: https://requirejs.org/docs/errors.html#scripterror

Took reference from:

  1. https://github.com/ALM-Rangers/Show-Area-Path-Dependencies-Extension/blob/master/src/VSTS.DependencyTracker/vss-extension.json for vss-extension file.
  2. https://github.com/ALM-Rangers/Show-Area-Path-Dependencies-Extension/blob/master/src/VSTS.DependencyTracker/index.html for index.html

Solution

  • I am afraid that you couldn't directly get the content of the json file.

    But you could try to use the HTTP request to get the content.

    Please refer to the following sample:

     onFieldChanged: function (args) {
                            var request = new XMLHttpRequest();
                            request.open('GET', 'config.json', true);
                            request.send(null);
                            request.onreadystatechange = function () {
                                if (request.readyState === 4 && request.status === 200) {
                                    var type = request.getResponseHeader('Content-Type');
                                                    console.log( "inside onfield : " + JSON.stringify(request.responseText));
                                }
                            }
    

    Check out these two tickets for details.

    Loading a JSON file in a VSTS extension

    read local JSON file into variable