JavaScript Development Space

Using TypeScript in HTML with Webpack Setup

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
1 {
2 "compilerOptions": {
3 "outDir": "./dist",
4 "module": "ESNext",
5 "target": "ES6",
6 "moduleResolution": "Node"
7 }
8 }

3. Configure Webpack

Create webpack.config.js:

js
1 const path = require('path');
2
3 module.exports = {
4 entry: './src/index.ts',
5 output: {
6 filename: 'bundle.js',
7 path: path.resolve(__dirname, 'dist'),
8 },
9 resolve: {
10 extensions: ['.ts', '.js'],
11 },
12 module: {
13 rules: [
14 {
15 test: /\.ts$/,
16 use: 'ts-loader',
17 exclude: /node_modules/,
18 },
19 ],
20 },
21 mode: 'development',
22 };

4. Create TypeScript Code

Create src/math.ts:

ts
1 export class MathUtils {
2 static add(a: number, b: number): number {
3 return a + b;
4 }
5 }

5. Build and Run Webpack

Run Webpack to compile the TypeScript files:

npx webpack

6. Use in an HTML Page

Create index.html:

html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>TypeScript with Webpack</title>
7 </head>
8 <body>
9 <script src="./dist/bundle.js"></script>
10 </body>
11 </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.

JavaScript Development Space

JSDev Space – Your go-to hub for JavaScript development. Explore expert guides, best practices, and the latest trends in web development, React, Node.js, and more. Stay ahead with cutting-edge tutorials, tools, and insights for modern JS developers. 🚀

Join our growing community of developers! Follow us on social media for updates, coding tips, and exclusive content. Stay connected and level up your JavaScript skills with us! 🔥

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.