I have a TypeScript library that I've created. I need to know how to import and use this library in a browser. First, I am using tsc v2.1.4; I am also using gulp's TypeScript plugins to help with the development process. I have a gulp task that compiles my *.ts
files to *.js
files as follows.
gulp.task('dist', function() {
var tsResult =
gulp.src(['src/**/*.ts'])
.pipe(sourcemaps.init())
.pipe(tsc({ out: 'mylib.js', noImplicitAny: true, target: 'es6', sourceMap: true, module: 'system' }));
return tsResult.js
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'));
});
The generated mylib.js
file looks something like the following.
System.register("vehicle/car",[], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var Car;
return {
execute: function() {
Car = class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
};
exports_1("Car", Car);
};
});
I then attempt to follow the documentation on SystemJS and create a index.html
to test usage.
<html>
<head>
<title>Test MyLib</title>
</head>
<body onload="start()">
<script src="node_modules/systemjs/dist/system.js"></script>
<script>
function start() {
SystemJS.import('dist/mylib.js')
.then(function(lib) {
console.log(lib);
//what do i do here? how do i use my classes/objects here?
});
}
</script>
</body>
</html>
Looking at the JavaScript console, I see no errors. Where I log the lib
out, it is just an Object
with a bunch of functions that I'm not sure how to use to instantiate the classes/objects from my library.
I'm continuing to read more on how this TypeScript to ES6 to ES5 stuff works. Apparently, even though I've generated a JavaScript file (e.g. mylib.js
) I just can't simply reference it like
<script src="dist/mylib.js"></script>"
and then use it. I have to go through SystemJS
(which I'm new to and is a part of the confusion). Apparently, it seems like I can just reference my *.ts
files directly and use other plugins (babel) with SystemJS to transpile on the fly. It doesn't help that the documentation on babel systemjs plugin is out of date (the usage instructions is out of date it seems).
The SystemJS usage instructions are a bit confusing too. In some cases I see SystemJS.config({...})
and in some cases I see System.config({...})
. I'm speculating they changed SystemJS
from System
, but I'm really not sure.
I'd appreciate clarification on how to go from a TypeScript library project all the way browser usage; any online examples or guidance on here is appreciated (and I'm continuing to search as well).