When importing a module, the function in the ts file may not be recognized or located

While attempting to create a VSTS (Azure Devops) Extension, I encountered a perplexing issue.

Within my HTML page, I have a button element with an onclick listener:

<!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"
}

Initially, everything worked smoothly. However, upon importing a module into the .ts file, I encountered an error stating that the function "btnEvent" could not be found.

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

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

I spent 2 hours researching this issue, but unfortunately, I was unable to find a solution.

Answer №1

When you neglect to include the import statement, your TypeScript file is viewed as existing within the global scope. However, by adding the import statement, the file transitions into being treated as a module. In order for your function to be visible outside of the file, it needs to be exported. Simply prepend the export keyword before your function.

For further information, please see: Modules - TypeScript

In TypeScript, similar to ECMAScript 2015, any file that includes a top-level import or export is recognized as a module. On the other hand, a file lacking any top-level import or export declarations is interpreted as a script whose contents are accessible in the global scope (and thus to modules too).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty modifying styles within the React Material-UI app bar component

I created a unique component and tried to implement it in AppBar, but the styles are not being overridden. I utilized the makeStyles hook which works perfectly fine outside of the AppBar, however, within the AppBar and ToolBar, I am encountering difficulti ...

Attempting to invoke a promise within a function yields an error message stating that it lacks call signatures

Recently, I came across this interesting class: export class ExponentialBackoffUtils { public static retry(promise: Promise<any>, maxRetries: number, onRetry?: Function) { function waitFor(milliseconds: number) { return new Pr ...

Is there a way to split each foreach value into distinct variables?

I am looking to assign different variables to foreach values. I have fetched data from an API in JSON format, and then echoed those values using a foreach loop. My goal is to display the echoed value in an input box using JavaScript. I attempted the follow ...

Harness the power of TypeScript in a single test file with jest's expect.extend() method

This question is similar to Can you limit the scope of a TypeScript global type? but it presents a slightly different scenario that requires clarification (although an answer to this would be greatly appreciated as well). In my Jest setup, I am attempting ...

What could be the reason for this simple sails socket not functioning properly?

Just curious why the simple web socket code below isn't functioning? io.socket.on('user', function(event){ console.log("RECEIVED EVENT:",event); }) I have included sails.io.js in my index file and the above code is located in a test.js ...

In jQuery, utilizing dynamic class names with variables

I have a series of images with unique classes such as: .1a .2a .3a .4a ..... I am looking to toggle some other classes named .1b .2b .3b .. and so on so that: '.1a' toggles to '1b' '.2a' toggles to &ap ...

Issue with returning value from promise object in Next.js

Hello! I am fairly new to JS and React, so I would appreciate your patience as I try to navigate through this. It has been quite a journey so far. In my component, I am fetching JSON data from a URL and attempting to extract a specific value from it to d ...

What is the best way to dynamically pass JSON object values to PHP?

Greetings, I am new to JSON and Ajax. Although my question may seem trivial, I believe that even the simplest inquiries are crucial in the learning process. My dilemma involves passing two parameters (giorno and periodo) via Ajax: For example: 'gior ...

Focus on input using jQuery (fixed focus)

How can I ensure that my input always has value and the focus remains fixed on it until values are typed, preventing the cursor from escaping the input field? While I know the existence of the focus() function, how can I effectively utilize it as an event ...

Circular dependency in Typescript/Javascript: Attempting to extend a class with an undefined value will result in an error,

Query Greetings, encountering an issue with the code snippet below: TypeError: Super constructor null of SecondChild is not a constructor at new SecondChild (<anonymous>:8:19) at <anonymous>:49:13 at dn (<anonymous>:16:5449) ...

I am currently facing an issue in my Node.js environment specifically with the 'oracledb' package

I am encountering an issue with the oracledb modules. Fortunately, I was able to successfully install oracledb. When I run the command like this, -> npm install oracledb njsOracle.cpp njsPool.cpp njsConnection.cpp njsResultSe ...

A problem encountered in specific JavaScript code

As a newcomer to JavaScript, I have encountered an issue while trying to run this script: <html> <head> <title>Exploring javascript functionalities</title> </head> <body> <p id="demo">I ...

Generating pop-up upon loading with CSS3

I have searched through numerous threads and forums in the hopes of finding a solution, but I haven't been successful. My issue lies with triggering a popup on my website. I followed online tutorials to create a popup window, which I was able to do su ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

Adding inline SVGs to a Nuxt 3 Vite project: A step-by-step guide

Hey there, I've been struggling with importing inline SVGs into my Nuxt3 Vite project. Any advice would be greatly appreciated. I discovered that using <img src="~/assets/images/icons/push-icon-chatops.svg" /> works, but I actually ne ...

Automatically update the div every few seconds and pause when it has loaded successfully

I am facing a challenge in creating a div that refreshes automatically every 10 seconds, but stops when it successfully loads. Here is the jQuery script I have developed: <script type="text/javascript"> $(document).ready(function(){ var j = jQuer ...

Uncovering Inline Styles Infused with Javascript for Effective Debugging of Javascript Code

SITUATION: I have recently inherited a website from the previous developer who has scattered important functions across numerous lengthy JS files. I am struggling to track down the source of an inline CSS style within the JS or identify which function is d ...

Is there a minimum height restriction for v-select in Vuetify.js?

Looking at the code snippet provided below, I am facing an issue while trying to decrease the height of a v-select element. It seems like there is a minimum limit set for the height, as reducing it beyond height = 40 doesn't have any effect. Is there ...

The Issue of Anti Forgery Token Not Functioning Properly with Ajax JSON.stringify Post

I have been attempting to utilize an Anti Forgery token with JSON.stringify, but despite researching multiple sources, I have not been successful. Below is my AJAX code for deleting some information without any issues. Upon adding the anti forgery token, I ...

In what way can I decipher a section of the URL query string within my AngularJS application?

Here is a snippet of code that I am working with: var search = $location.search(); if (angular.isDefined(search.load) && search.load != null) { if (search.load = "confirmEmail") authService.confirmEmailUserId = search.userI ...