Skip to content Skip to sidebar Skip to footer

How To Call TypeScript Functions Out Of The .ts Files?

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. Just imagine very simp

Solution 1:

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");

Solution 2:

How to design API of my library in TypeScript? (any good resource)

Really a build tool chain question. If you want to expose your library as a global the answer is dependent on your toolchain. I recommend using webpack. Here is a a sample config:

module.exports = {
    /** Build from built js file */
    entry: {
      typestyle: './lib/index.js',
    },
    output: {
        filename: './umd/typestyle.js',
        libraryTarget: 'umd',
        /** The library name on window */
        library: 'typestyle'
    }
};

From the TypeStyle project.


Post a Comment for "How To Call TypeScript Functions Out Of The .ts Files?"