Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gulp + Browserify + TypeScript To Browser

My problem is the following:

I use gulp+browserify to compile my TypeScript to JavaScript that you can use on normal HTML pages, the problem is that my class is never available on the browser:

VM633:1 Uncaught ReferenceError: Test is not defined
    at <anonymous>:1:13

This is my TypeScript File:

class Test {
        public test(): void {
            console.log("aa");
        }
}

This is my gulpfile

var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");

gulp.task("default", function () {
    return browserify({
        //basedir: '.',
        debug: true,
        entries: ['app/Resources/typescript/Test.ts'],
        cache: {},
        packageCache: {}
    })
        .plugin(tsify)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest("web/bundles/framework/js"));
});

The file compiles without problem, and is included in my index.html (the compiled js file).

But when i try:

 var t = new Test();

I get the following error:

VM633:1 Uncaught ReferenceError: Test is not defined
    at <anonymous>:1:13

I can't resolve it, I have read a lot and I haven't found anything clear, I tried all and nothing worked.

like image 258
redigaffi Avatar asked Nov 08 '22 16:11

redigaffi


1 Answers

There are a few things missing here:

If you want your class to be accessible outside of your module, you have to export it:

export class Test {
    // ...
}

Browserify creates functions on top of the classes you define. So it won't be accessible globally (which is a good thing). Normally you would import it in another file and use it:

// in any TS file that wants to use `Test` class. Make sure this is included in the gulp entries as well
import {Test} from "test";
var t = new Test();
console.log(t);

Or if really want it to be accessible globally, you can attach it to window object:

// In Test.ts file:

(window as any).Test = Test; // This can be useful when debuging. But don't do this in production code.
like image 147
Saravana Avatar answered Nov 14 '22 21:11

Saravana