Combining modules with TypeScript
In the previous post, I showed how to use TypeScript modules to create small units of independent and reusable code. Creating small modules is very great. However, at runtime, you may want to download only 1 file instead of tens of files. The solution is to combine all your files into one.
To combine files, you can use a tool such as UglifyJS or just concatenate files. If you use AMD or System modules, you can configure TypeScript to output a single file with all your modules. Open the tsconfig.json
file and set outFile
:
{
"compilerOptions": {
"module": "system",
"outFile": "file.js"
}
}
The output file will contain all your modules in file.js
:
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));
}
};
});
Then you can include this file into your code. As we know we'll load the file, we can include it directly on the page in addition to SystemJS
. Then, you still have to load the main module using SystemJS:
<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 solution is very convenient if you don't want to set up a complex build workflow.
Do you have a question or a suggestion about this post? Contact me!