How to compile few typescript files to single output js-file?


TypeScript is a strongly typed superset of JavaScript that compiles to plain JavaScript. TypeScript adds static type-checking, classes, and interfaces to the language, making writing and maintaining large-scale applications easier. TypeScript files are compiled into JavaScript files that can be run in any browser or server that supports JavaScript. This article will look at how to compile multiple TypeScript files into a single output js-file.

We will start by looking at how to use the TypeScript compiler to compile multiple TypeScript files and then see how to use Webpack to bundle multiple TypeScript files into a single JavaScript file.

Compiling Multiple TS Files Into Single JS File Using `tsc`

The TypeScript compiler is a command-line tool that can be used to compile TypeScript code to JavaScript. To install the TypeScript compiler, open a terminal and run the following command −

npm install -g typescript

Next, we need to create a tsconfig.json in the root of our project. The tsconfig.json file contains configuration options for the TypeScript compiler.

Here is an example tsconfig.json file −

{
   "compilerOptions": {
      "target": "ES2015",
      "outFile": "out/bundle.js",
      "module": "amd",
      "sourceMap": true,
   },
   "include": [
      "src/**/*.ts"
   ]
}

In this example configuration, we have used the TypeScript compiler with options such as target, outFile, module, sourceMap, and include. These options specify the ECMAScript version which is set to ES2015, output file name which is set to out/bundle.js, module system for which we have two options amd or system and is set to amd, source map generation which is set to true, and files to be included in the compilation. We have specified all the files inside the src directory and its subdirectories to be included for compilation.

To compile our TypeScript code, we can run the following command in the terminal −

tsc

This will compile all TypeScript files in the "src" directory and its subdirectories into a single JavaScript file located at "out/bundle.js".

Example 1

For this example, we’ll create two TypeScript files, namely src/index.ts and src/app.ts. Follow the below commands to create empty files with these names −

$ touch src/app.ts src/index.ts
$ touch tsconfig.json

Now, we will configure the TypeScript compiler by setting up the tsconfig.json

touch tsconfig.json

Now, paste the above configuration options to the tsconfig.json file by modifying the outFile value to out/bundle.js.

Also, paste the following codes to corresponding files −

src/app.ts

export default interface Person {
   firstName: string, 
   lastName: string,
   sayHello(): void, 
}

This declares and exports an interface named Person with two properties firstName and lastName and one method sayHello.

src/index.ts

import Person from "./app"
class Employee implements Person {
   firstName: string 
   lastName: string 

   constructor (firstName: string, lastName: string) {
      this.firstName = firstName,
      this.lastName = lastName
   }
   sayHello() {
      console.log(`Hello, ${this.firstName + this.lastName}`)
   }
}
const obj = new Employee("Aditya", "Singh")
obj.sayHello()

This files imports the exported Person interface and implements a class on it.

Now, to compile all these (two files in this case) files run −

tsc

Output

out/bundle.js

define("app", ["require", "exports"], function (require, exports) {
   "use strict";
   Object.defineProperty(exports, "__esModule", { value: true });
});
define("index", ["require", "exports"], function (require, exports) {
   "use strict";
   Object.defineProperty(exports, "__esModule", { value: true });
   class Employee {
      constructor(firstName, lastName) {
         (this.firstName = firstName), (this.lastName = lastName);
      }
      sayHello() {
         console.log(`Hello, ${this.firstName + " " + this.lastName}`);
      }
   }
   const obj = new Employee("Aditya", "Singh");
   obj.sayHello();
});
//# sourceMappingURL=bundle.js.map

A new file out/bundle.js will be created containing a single compiled JS file. This compiled JS file contains AMD (Asynchronous Module Definition) module, and for running these with node, we first have to convert it to a format using webpack or rollup bundler which Node.js can understand. This is the limitation of using tsc to compile multiple TypeScript files into a single TypeScript file.

Compiling Multiple TS Files into Single JS File Using Webpack

Webpack is a popular build tool for modern web development that can be used to bundle and optimize JavaScript files, but it also has built-in support for TypeScript through loaders. Webpack uses tsc under the hood to transpile the .ts files. ts-loader is used as a glue between webpack and tsc. So, you’ll still need your tsconfig.json file.

Example 2

We will build on our previous example and compile the two TypeScript files that we previously created into a single JS file usingwebpack.

To use webpack to transpile TS files to JS files, you will need to install the necessary dependencies, including webpack, webpack-cli, and ts-loader

npm install webpack webpack-cli ts-loader

Once you have installed these dependencies, you can create a Webpack configuration file, webpack.config.js, in your project directory. Here is an example configuration file −

Configuration file (webpack.config.js) −

const path = require('path');
module.exports = {
   entry: './src/app.ts',
   mode: 'development',
   devtool: 'inline-source-map',
   watch: true,
   output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist'),
   },
   resolve: {
      extensions: ['.ts', '.js'],
   },
   module: {
      rules: [
         {
            test: /\.ts$/,
            use: 'ts-loader',
            exclude: /node_modules/,
         },
      ],
   },
};

In this configuration file, the entry property specifies the entry point for your application, which is a TypeScript file (app.ts in this example). The mode property specifies the build mode (development in this example), and the devtool property specifies the source map type. The output property specifies the output filename and directory, and the resolve property specifies the file extensions to resolve. Finally, the module property specifies the loaders for different file types, including the ts-loader for TS files.

The watch option set to true specifies Webpack to run in the background and compile automatically whenever saved changes are detected in the .ts files.

To compile all the .ts files (src/index.ts and src/app.ts in this case), we just need to run −

npx webpack

This will create a dist/bundle.js file containing a single bundled .js file.

Output

A new file dist/bundle.js will be created which you can run in the Node.js environment using −

node dist/bundle.js

In the terminal you will get output as −

Hello, Aditya Singh

Conclusion

We discussed two approaches for compiling multiple TypeScript files into a single JavaScript file - using the TypeScript compiler or using Webpack. The TypeScript compiler is simple and requires minimal configuration with its limitations of only AMD and system modules. At the same time, webpack generates JS files in almost all modules types like commonjs but is more complex to configure. Any of the two approaches can be selected based on the project needs.

Updated on: 21-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements