How to call TypeScript functions out of the .ts files?

后端 未结 2 581
青春惊慌失措
青春惊慌失措 2021-01-28 23:09

I have a very simple program to learn how to work with TypeScript, I bundled all my .ts files using Browserify to make it possible to run inside the browser.

<
2条回答
  •  心在旅途
    2021-01-28 23:20

    your code should work as expected, you just need to add standalone to your Browserify config

    This should be your Browserify task on Gulp:

     return browserify({
            standalone: "yourLib",
            basedir: '.',
            debug: true,
            entries: ['src/main.ts'],
            cache: {},
            packageCache: {},
        })
    

    Look at standalone: "yourLib".


    Now you need to export something in your main.ts file, for example:

    //main.ts
    export function whatsYourName(name:string){
     console.log(name);
    }
    

    Now just run your gulp build task (which will compile and browserify/bundle your ts files), include that bundled script into your page, open Chrome console (F12) and inside the console tab just write the name of what you defined for standalone in your browserify task (here we named that yourLib).

    For our example, you just need to type this in the console to get the response:

    yourLib.whatsYourName("Alex");
    

提交回复
热议问题