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

后端 未结 2 579
青春惊慌失措
青春惊慌失措 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");
    
    0 讨论(0)
  • 2021-01-28 23:37

    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.

    0 讨论(0)
提交回复
热议问题