Example on integrating TypeScript with Webpack

Summary

Integrating TypeScript with Webpack streamlines development by bundling typed JavaScript code. The core mechanism involves installing ts-loader, which Webpack then utilizes to compile .ts and .tsx files into standard JavaScript. This setup requires configuring package.json for dependencies and scripts, webpack.config.js to define entry/output and specify ts-loader in module rules, and a tsconfig.json for TypeScript compiler options. Executing the webpack command triggers the compilation and bundling process, resulting in a single JavaScript file in the designated output directory, ready for browser consumption.

TypeScript is now a very popular language to create typed JavaScript code to reduce development error. It provides a type system on top of JavaScript which has only a weak type system. Once the TypeScript code is developed, it can be compiled into corresponding JavaScript so that they can be loaded and parsed by browser.

Webpack is another tool for bundling multiple JS files into a single one so that no multiple connections to be established between browser and server. when a page is loaded This would reduce the bandwidth consumption and improve website performance in general.

These two are good add-ons for developers to improve development speed and efficiency. If they both can work together so that they can be integrated into the same build pipeline, it would be great. There is a detailed post explaining how to integrate TypeScript with Webpack. In this post, we will show an example to explain the process at code level.

The key here is to have a ts-loader package installed so that it can be invoked by webpack to compile TypeScript code into JavaScript code and output.

Below is the file structure in the project before running the webpack tool.

It has two TS files which are to be bundled into one single JS file. Also it has TypeScript config file, webpack config file and node package.json which is the entry point of the build process.

The package.json file looks like:

{
  "name": "ts2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "webpack": "^5.24.4",
    "webpack-cli": "^4.5.0"
  },
  "devDependencies": {
    "install": "^0.13.0",
    "ts-loader": "^8.0.17",
    "ts-node": "^9.1.1",
    "typescript": "^4.2.3"
  },
  "scripts": {
    "test": "webpack"
  },
  "author": "",
  "license": "ISC"
}

When running npm run test, it will find the scripts section and run the webpack as pointed by test. Once webpack runs, it will then load the webpack.config.js. The config content is:

const path = require('path');  // node package
module.exports = {
    entry: './test.ts',   // entry point for the TS
    output: {
        filename: 'test.js',   // output file name
        path: path.resolve(__dirname, 'dist')  // output directory
    },
    mode: 'development',   // mode defines the mode of output env
    module: {
        rules: [{
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/
        }]
    },
    resolve: {
        extensions: ['.ts']      // file extensions to be concerned
    },
}

This tells the webpack command to start to find test.rs in current working directory and then generate the output file in dist folder with name test.js. And the mode is development, it can be other environment as well such as production if wanna bundle differently.

The module rules tells it uses ts-loader to compile all the .ts or .tsx files and exclude those in the node_modules folder.

When ts-loader runs, it will try to also load the config from tsconfig.json.

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    "target": "es5",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "outDir": "./js",                               /* Redirect output structure to the directory. */

    /* Strict Type-Checking Options */
    "strict": true,                                 /* Enable all strict type-checking options. */

    /* Module Resolution Options */
    "moduleResolution": "node",                  /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

    /* Advanced Options */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
  }
}

This is a pretty standard TS config file which doesn't need specific explanation. 

Now coming to the content for test.ts and index.ts

// test.ts
import { hello } from "./index";
hello();

// index.ts
export function hello() {
    console.log("hello world");
}

Now run npm run test, it will have below output.

$ npm run test
Debugger listening on ws://127.0.0.1:8045/d0cd3ed2-eb40-4cbd-8b54-0e9bd25212ac
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.

> [email protected] test D:\Project\TypeScript\ts2
> webpack

Debugger listening on ws://127.0.0.1:8052/6a4357ba-1975-43d1-92da-ab39e7b0b2b2
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
asset test.js 2.64 KiB [emitted] (name: main)
./test.ts 132 bytes [built] [code generated]
./index.ts 184 bytes [built] [code generated]
webpack 5.24.4 compiled successfully in 3671 ms
Waiting for the debugger to disconnect...
Waiting for the debugger to disconnect...

Now a test.js file will be generated in dist folder.

Once this is done, in HTML code, just reference the ./dist/test.js to make it work.

JAVASCRIPT EXAMPLE TYPESCRIPT WEBPACK

  RELATED

  COMMENTS

0

No comment for this article.