How to Use TypeScript in HTML: Complete Webpack Setup Guide

Using TypeScript in an HTML page requires proper module bundling, and Webpack simplifies this process. This guide walks you through setting up Webpack to compile TypeScript and use it in an HTML page.

1. Project Setup

Initialize a new project and install dependencies:

npm init -y

npm install typescript webpack webpack-cli ts-loader —save-dev

2. Configure TypeScript

Create tsconfig.json:

json
12345678
      {
  "compilerOptions": {
    "outDir": "./dist",
    "module": "ESNext",
    "target": "ES6",
    "moduleResolution": "Node"
  }
}
    

3. Configure Webpack

Create webpack.config.js:

js
12345678910111213141516171819202122
      const path = require('path');

module.exports = {
  entry: './src/index.ts',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  mode: 'development',
};
    

4. Create TypeScript Code

Create src/math.ts:

ts
12345
      export class MathUtils {
  static add(a: number, b: number): number {
    return a + b;
  }
}
    

5. Build and Run Webpack

Run Webpack to compile the TypeScript files:

npx webpack

6. Use in an HTML Page

Create index.html:

html
1234567891011
      <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TypeScript with Webpack</title>
  </head>
  <body>
    <script src="./dist/bundle.js"></script>
  </body>
</html>
    

Conclusion

With Webpack, you can efficiently compile and bundle TypeScript for use in an HTML page. This setup ensures a modular and maintainable development workflow.