Embarking on a journey to familiarize myself with TypeScript, I undertook a straightforward program by bundling all my .ts
files using Browserify for browser compatibility.
Picture a basic variable declaration in TypeScript:
main.ts
let testVar = "Something";
Here's the content of my gulpfile.js
for compilation and bundling purposes:
'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'));
});
As for 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 functions smoothly, and the TypeScript code operates as intended. However, upon including the compiled and bundled code in my .html file and attempting to access the testVar variable by simply calling it in the Chrome console using console.log(testVar);
, an error is returned:
Uncaught ReferenceError: testVar is not defined
Below 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 within the bundled .js
file?
What approach should I follow to design the API of my library in TypeScript? (any recommended resources)