In the previous post, I showed how to use TypeScript modules to create small, independent, and reusable units of code. While small modules are great for maintainability, at runtime you often want to serve a single file rather than dozens. The solution is to combine all your files into one.
To combine files, you can use a tool such as UglifyJS or simply concatenate them. If you use AMD or System modules, TypeScript can be configured to output a single bundled file. Open tsconfig.json and set outFile:
JSON
{
"compilerOptions": {
"module": "system",
"outFile": "file.js"
}
}
The output file will contain all your modules in file.js:
JavaScript
System.register("math", [], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
function add(a, b) {
return a + b;
}
exports_1("add", add);
return {
setters: [],
execute: function () {// file math.ts
}
};
});
System.register("main", ["math"], function (exports_2, context_2) {
"use strict";
var __moduleName = context_2 && context_2.id;
var math_1;
return {
setters: [
function (math_1_1) {
math_1 = math_1_1;
}
],
execute: function () {
console.log(math_1.add(1, 2));
}
};
});
You can then include this file in your page alongside SystemJS. You still need to load the main module using SystemJS:
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.20.19/system.js" integrity="sha256-HCJlhCZ21EKx0Wo6wCF+rbeBHlVlOSJccd4zTQe2TNw=" crossorigin="anonymous"></script>
<script src="file.js"></script>
<script>
// Load the main module
SystemJS.import("main");
</script>
This approach is convenient when you want to avoid setting up a complex build workflow.
Do you have a question or a suggestion about this post? Contact me!