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:
2. Configure TypeScript
Create tsconfig.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
:
1 const path = require('path');23 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
:
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:
6. Use in an HTML Page
Create index.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.