I have a javascript file called ui.js.
Inside ui.js is UI setup code.
if (!("ontouchstart" in document.documentElement)) { document.documentElement.className += " no-touch"; var jScrollOptions = { autoReinitialise: true, autoReinitialiseDelay: 100 }; $('.box-typical-body').jScrollPane(jScrollOptions); $('.side-menu').jScrollPane(jScrollOptions); $('.scrollable-block').jScrollPane(jScrollOptions); }
I would like to be able to call this from typescript.
I don't want to convert the code to typescript as there are hundreds of lines and it's not really necessary. It just needs to be one once after the UI is ready.
It seems to me that I should be able to wrap it in a function, and then call that function from typescript.
But I have not been able to figure out how to do that.
Note: Not a duplicate of earlier question, as that was how to convert js, not use it directly with as little modification as possible.
The allowJs setting allows JavaScript files to be imported inside your TypeScript files. The setting basically allows JavaScript and TypeScript files to live in the same project.
First, we read the file content of TS and use the transpileModule method provided by the typescript module to compile the TS code into JS code, get the JS code string of outputText , and finally use the native API Module. prototype. _compile provided by Node. js to compile and execute the JS code string.
You have two main options.
Simply set allowJs
to true in your tsconfig.json compilerOptions
and then make sure the .js
file is included using files
/include
/exclude
etc.
e.g. if you are going to call a js function anExampleFunction
you can simply create a declaration (in a .d.ts
file):
declare const anExampleFunction: Function;
And now you will be able to call the function from TypeScript.
You can call JavaScript functions from external files with no worries. But you have to declare them so TypeScript knows about them. If you dont, your code will work, but you will get an error while compiling.
You can use an Anonymously-typed var:
declare var myFunction;
or an Interfaced-typed var:
interface __myFunction { } declare var myFunction: __myFunction;
You may also write this into a declaration file(but its not required). See also TypeScript documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With