0

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 simple variable declaration in TypeScript:

main.ts
let testVar = "Something";

And here is my gulpfile.js to compile (and bundle the files when needed):

'use strict';

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


gulp.task('build',['minify'], function () {

    return browserify({
        basedir: '.',
        debug: true,
        entries: ['src/main.ts'],
        cache: {},
        packageCache: {}
    })
        .plugin(tsify)
        .bundle()
        .pipe(source('main.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest("dist"));

});

gulp.task('minify',function () {
    gulp.src('dist/main.js')
        .pipe(minify({
            ext:{
                src:'.js',
                min:'.min.js'
            },
            ignoreFiles: ['.min.js']
        }))
        .pipe(gulp.dest('dist'));
});

and this is my tsconfig.json

{
  "compilerOptions": {
    "module": "system",
    "sourceMap": true,
    "lib": ["dom", "es2015.promise", "es5"],
    "noImplicitAny": true,
    "target": "es2015"
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "src/**/*"
  ],
  "files": [
    "src/**/*"
  ]
}

The build task work as expected, and what that I have inside the typescript works well too. But, when I include the bundled and compiled into my .html file, and trying to access the testVar variable. by just easily calling it in Chrome console, console.log(testVar); but it returns error:

Uncaught ReferenceError: testVar is not defined

And here is the compiled + bundled .js file:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
let testVar = "Something";
},{}]},{},[1])

//# sourceMappingURL=main.js.map

How can I access the functions and variables inside the bundled .js file? How to design API of my library in TypeScript? (any good resource)

2 Answers2

3

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");
Mohammad Kermani
  • 5,188
  • 7
  • 37
  • 61
  • Am I able to add a class with static functions to the library? I am new to JS and TypeScript and want to call a static function in my js file: `var test = MyClass.doSomething();` MyClass is in a TypeScript file like "MyClass.ts" and will be bundled and minified via browserify. – Ismoh Nov 17 '17 at 14:45
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.

basarat
  • 261,912
  • 58
  • 460
  • 511
  • Are not we able to use CommonJs/system and also being able to access variables and functions? I used umd, but the file become very large! about 100k – Mohammad Kermani Feb 15 '17 at 07:54
  • I found the tsconfig and gulpfile configs from the TypeScript project website, for bundling files... but they said nothing about how to work with the ts functions when we included inside the browser – Mohammad Kermani Feb 15 '17 at 08:08
  • Can you please describ more? I see people talk about Commonjs modules and mine is also commonjs but it is not working in browser, no error in output, but I don't know how to run it! – TypeScript Learner Feb 15 '17 at 19:26
  • @TypeScriptLearner I had the same problem, Please take a look at my answer, that solved my problem. http://stackoverflow.com/a/42268460/3176270 – Mohammad Kermani Feb 16 '17 at 08:25
  • @M98 Thanks, I think the **libraryTarget** in Webpack is same as **standalone** in browserify. – TypeScript Learner Feb 16 '17 at 18:18