What is the best way to bring in a variable initialized by an IIFE from a JavaScript file into a TypeScript class?

I'm currently working towards integrating the steelseries.js library (found at https://github.com/HanSolo/SteelSeries-Canvas) into a Grafana plugin built with React. It's quite a complex task, but I'm up for the challenge.
Right now, my main focus is on importing the steelseries variable into a TypeScript class.
Essentially, I have a large JavaScript file (over 10,000 lines) structured like this:

var helloWorld = (function() {

    var helloDisplay = function () {
        console.log("Hello World");
    }
    return {msgDisplay : helloDisplay}

}) ();

My goal is to import this script into a TypeScript class as shown below:

// how to import my JS script in myJs ?

class MyClass {
    ...
    tsHello (): void {
        myJs.msgDisplay()
    }
}

I'm looking for the simplest and most efficient way to achieve this, considering the length of the JS file. (I've tried various methods, including adding .d.ts files, but haven't had much success so far).

Answer №1

Maybe not the most conventional approach, but it gets the job done effectively and easily.

  1. Include configuration in tsconfig.json file :
    "compilerOptions": {
         "target": "es5",
         "module": "es6",
         "strict": true,
     }
    
  2. Add export statement in your JavaScript file:
    export var helloWorld = (function() { ...
  3. Create a corresponding .d.ts file for typings:
    export var helloWorld: any;
  4. Import the module in your TypeScript file:

    import { helloWorld as myJs } from './varIIFE'
     class MyClass {
         tsHello () {myJs.msgDisplay()}
     }
    let myInstance = new MyClass();
    myInstance.tsHello()

  5. Modify HTML to include the generated JavaScript file with module attribute:

    <script src="compilatedfile.js" type="module"></script>

Answer №2

Are you finding this beneficial?

interface Greetings{
  displayMessage():void,
  bar:string,
  count: number
}

var greetings = (function():Greetings {

  var messageDisplay = function () {
      console.log("Hello World");
  }
  return {
    displayMessage : messageDisplay,
    bar: 'foo',
    count: 456
  }

})()

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

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...

Methods for invoking a JavaScript function from TypeScript within an Angular2 application

Hey there! I'm looking to execute a regular JavaScript function from a TypeScript file. Let's say I have a JavaScript file called test.js and it's been imported into the index.html of my application. Now, I want to invoke the test() functi ...

Generating a unique user ID similar to Zerodha's user ID using Node.js/JavaScript

For a project I'm working on, I need to create random and unique User IDs. I came across Zerodha's user IDs which are easy to remember. In Zerodha user IDs: The first two characters are always letters followed by four numbers. I want to generat ...

Access the value of a submitted form using jQuery, when there are multiple forms with identical class names

I've looked for a solution here but couldn't find one that meets my needs. I have multiple forms with the class name .sbt-form: <form class='sbt-form'> <input name='kord' val=1/> </form> <form class= ...

Sliding the container with a width adjustment and left margin fails to display all images

In the provided HTML code below, there is a functionality to move images horizontally by clicking on buttons: $(document).ready(function() { calculate_width(); $('#moveleft').click(function() { var loga = $('#marki #loga'); ...

Flex-Layout in Angular - The Ultimate Combination

Recently, I decided to delve into Angular and the Flex-Layout framework. After installing flex-layout through npm, I proceeded to import it in my app.module.ts file like so: import { FlexLayoutModule } from '@angular/flex-layout'; imports: [ Fl ...

Is there a way to send arguments to a pre-existing Vue JS application?

A Vue application we've developed connects to a Web Service to retrieve data. However, the URL of the web service varies depending on the installation location of the app. Initially, we considered using .env files for configuration, but realized that ...

Generate real-time dynamic line charts using data pulled directly from a MySQL database

I am in search of guidance on developing a real-time line chart that can dynamically update based on data fetched from MySQL. I need an example or reference on how to achieve this functionality without having to refresh the webpage every time new data is ...

Changing global properties in VueCli

Recently, I integrated a component library into my Vue 3 project. All instances of the component require the same styles. Instead of manually adjusting each instance's props, I opted to utilize a global property: app.config.globalProperties.$tooltipS ...

Adjust the size of an Angular component or directive based on the variable being passed in

I'm looking to customize the size of my spinner when loading data. Is it possible to have predefined sizes for the spinner? For example: <spinner small> would create a 50px x 50px spinner <spinner large> would create a 300px x 300p ...

Leveraging Angular js for performing operations in Putty

At the moment, we depend on Putty for connecting to the app server and checking logs. I am looking for a solution that would allow me to automate this process using angular js. Is it possible to send commands from my angular js or any other client-side a ...

After clicking on the "Delete Rows" button in the table, a white color suddenly fills the background in Angular Material

When the dialog box pops up, you'll see a white background color: https://i.stack.imgur.com/EflOx.png The TypeScript code for this action can be found in config-referrals.component.ts openDialog(action, obj) { this.globalService.configA ...

Passing an undefined value to the database via AJAX upon clicking a button

Hi there, I'm currently working on a table where I'm trying to perform an inline edit and update the value in the database by clicking on a button (an image). I've attempted to use an onclick function, but it seems to show "value=undefined&a ...

Error message: "The toJSON method is not found for the item in the nested array of

Encountering an issue with NSwag in my Angular project where it throws an error when attempting to send data if the object contains a nested array of objects like this: export interface IJobAdDto { mainJobAd: JobAddDetailsDto; differentLanguageJobA ...

Puppeteer exhibiting unexpected behavior compared to the Developer Console

My goal is to extract the title of the page using Puppeteer from the following URL: Here's the code snippet I am working with: (async () => { const browser = await puppet.launch({ headless: true }); const page = a ...

Creating a customized TextField look with styled-components and Material-UI's withStyles feature

Take a look at this customized TextField style with Material-UI's withStyles: export const StyledTextField = withStyles({ root: { background: 'white', '& label.Mui-focused': { color: 'white' }, ...

Assembly of these elements

When dealing with a structure where each property is of type These<E, A> where E and A are unique for each property. declare const someStruct: { a1: TH.These<E1, A1>; a2: TH.These<E2, A2>; a3: TH.These<E3, A3>; } I inte ...

Initiating an Ajax POST request when the onblur() event is triggered

Having an issue with Ajax. I'm trying to submit a changed value from an input field on the onblur() event, but there's a flicker that's bothering me. When I enter a new value and click away, the old value briefly flashes back before changi ...

Component fails to update when attribute is modified

My issue is that the crud-table component does not refresh when I change currentTable. It works when I assign currentTable = 'doctor' in the created() hook, but not here. Why is that? <template> <div id="adminpanel"> <div id ...

What is the method for specifying a null value in Typescript?

I'm curious if this code snippet is accurate, or if there's a better way to define it. Is there an alternative to using error!? I'm unsure of its meaning and would appreciate clarification. ...