简体   繁体   中英

How to Call Typescript Function From Index.html?

I've got an input element which tries calling a typescript function during the onchange event. However it doesn't work and I get the following error: inputChange is not defined . In my main.ts file, I've got a simple function called inputChange which just console logs "Hello World.".

// index.html    
<input onchange="inputChange()"/>

// main.ts
function inputChange(){
    console.log('Hello World!')
}

Does anyone know how I can access functions like inputChange from my index.html file? (Also everything else in my main.ts file works as normal but for some reason I can't access typescript functions/variables from index.html)

I'm using webpack and babel to compile the typescript file into a bundle.js which is then appended into my index.html file by HTMLWebpackPlugin.

This is my tsconfig file:

{
    "compilerOptions": {

        /* Basic Options */
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
        "lib": ["es6","dom"],                             /* Specify library files to be included in the compilation. */
        "allowJs": false,                       /* Allow javascript files to be compiled. */
        "sourceMap": true,                     /* Generates corresponding '.map' file. */

        /* Strict Type-Checking Options */
        "strict": true,                           /* Enable all strict type-checking options. */
        "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
        "strictNullChecks": true,              /* Enable strict null checks. */
        "strictFunctionTypes": true,           /* Enable strict checking of function types. */
        "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
        "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
        "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
        "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

        /* Additional Checks */
        "noUnusedLocals": false,          /* annoying when just testing */                // "noUnusedLocals": false,                /* Report errors on unused locals. */
        "noUnusedParameters": false,      /* annoying when just testing */                 // "noUnusedParameters": true,            /* Report errors on unused parameters. */
        "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

        /* Module Resolution Options */
        "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

        /* Advanced Options */
        "skipLibCheck": true,                     /* Skip type checking of declaration files. */
        "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
    },
    "compileOnSave": true,
    "exclude": ["node_modules"],
    "include": ["./public"]
}

This is one of the many reasons not to use onxyz -attribute-style event handlers: They require that the function you use has to be a global. It sounds like you have TypeScript set up to use modules, so top-level declarations in TypeScript files aren't globals.

Instead, hook up the handler to the input using JavaScript, identifying the input via where it is in the DOM, its class, or its ID. For instance, here's an example using an ID:

<input id="the-input">

and in your TypeScript code in the module where inputChange is defined (or another module that imports it):

document.getElementById("the-input").addEventListener("change", inputChange);

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