Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference javascript file inside typescript

I would like to use a javascript function inside a typescript file. How can I reference the javascript file containing that function inside typescript file?

I tried

<reference path="../libs/myjsfile.js" /> 

this brings an error while building like: Cannot resolve referenced file: ../libs/myjsfile.js

like image 997
user1160771 Avatar asked Oct 09 '14 08:10

user1160771


People also ask

How do I run a JavaScript file in TypeScript?

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.

How do you reference a file in JavaScript?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.


2 Answers

While the two answers above will work for a small or single variable API, the correct answer is to write a type declaration file for your JavaScript file.

The type declaration file for your example would be named myjsfile.d.ts, where the .d.ts suffix is what tells the TypeScript compiler that it's parsing a declaration file. If you use Visual Studio, your declaration file will be recognized by the TypeScript compiler as long as it is somewhere (anywhere) in the project you are working on.

Declaration files store metadata about JavaScript variables, functions and objects so the TypeScript compiler can do its job. If your JavaScript file happens to be a library or framework in common use, DefinitelyTyped is definitely the place to find the definition file you need.

If your JavaScript is your own work or less well known, you'll have to write your own type declaration file. See the section Writing .d.ts files in The TypeScript Handbook.

If the name declaration file sounds intimidating, don't worry - they are far easier to write than programs. Also, remember that you don't need to specify all metadata for your JavaScript file, just the functionality you need.

Let me know if you need any help!

like image 85
Doug Avatar answered Sep 29 '22 01:09

Doug


You just have to tell the compiler that the method exists outside typescript:

declare function myJavaScriptFunction(param1: number, param2: JQuery): void; 

Be sure that the website loads all files needed, the normal js files and the js files that the typescript compiler generated

like image 38
A. K-R Avatar answered Sep 29 '22 01:09

A. K-R