Search code examples
javascripttypescriptazure-devops-extensions

Function in ts file cannot be found when module is imported


I try to develope a VSTS (Azure Devops) Extension and do not understand the following behavior.

I have a html page with a button element and a onclick listener like:

<!DOCTYPE html>

<head>
    <script type="text/javascript">

        VSS.init({
            usePlatformScripts: true,
            moduleLoaderConfig: {
                paths: { "scripts": "scripts" }
            }
        });

        VSS.ready(function () { require(["scripts/btn-controller"], function () { }); });

    </script>
</head>

<body>
    <button class="active" onclick="btnEvent(event, 'Action')">Button</button>
    <input type="text" id="text">
</body>

</html>

The btn-controller.ts file:

function btnEvent(evt, NavTabButton) {
   document.getElementById("text").innerHTML = "works"
}

This works fine but when I import a module into the ts file I get the error that the function "btnEvent" cannot be found.

import Extension_Data = require("VSS/SDK/Services/ExtensionData");

function btnEvent(evt, NavTabButton) {
    document.getElementById("text").innerHTML = "should work"
}

I tried to find the reason for this behavior but after 2h research I was not able to find a working solution.


Solution

  • Without the import statement, the content of your ts file is treated as available in the global scope. When you add the import, the file starts to be treated as a module, so you have to export your function for it to be visible outside of the file. Just add the export keyword before your function.

    Reference: Modules - TypeScript

    In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).