简体   繁体   中英

How do I call a function in an external js file using typescrpt

We are trying a POC of adding Typescript and Webpack to our Angularjs project. I am able to get my webpack bundle to generate, however at runtime the program cannot find the various functions in my validator.js. Can you please offer some advice?

login-view.components.ts

declare var findFormNode: any;      //function in validator.js


 //LogInUser
 self.login = function ($event, command) {
     if (findFormNode($event.target.id)) {
     ...
     }
}  

main.ts is importing the file

import "./../../../CommonStaticFiles/include/js/Validators.js";

bundle.js

eval("/* WEBPACK VAR INJECTION */(function($) {/*\r\n\r\n  VALIDATORS\r\n\r\n ... n\n\nfunction findFormNode(

error

ReferenceError: findFormNode is not defined
at LoginController.self.login (login-view.component.ts:28)
at fn (eval at compile (angular.js:NaN), <anonymous>:4:267)
at callback (angular.js:29019)

In order for your functions to be properly imported, there are few things that you have to make sure of.

First, make sure you are exporting your functions correctly. Here's an example of how to export a function from Validator.js :

export const validateFunc1 = ():void => {};

Next, you have to make sure you are using proper import syntax. In order to import the function above, you would do the following:

import {validateFunc1} from "./../../../CommonStaticFiles/include/js/Validators.js";

Alternatively, if you want to import all exported functions at once, then you can use this syntax:

import * as validatorFuncs from "./../../../CommonStaticFiles/include/js/Validators.js";

Lastly, check that the location of Validators.js is correct. It's a common mistake to be looking in the wrong directory. Your code editor can usually help you find the right path to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM