April 1, 2019
How to Use Typescript with Webpack
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/js/index.ts',
mode: 'production',
resolve:{
extensions: ['.js', '.ts', '.tsx']
},
module:{
rules: [
{
test: /\.tsx?$/,
use:'ts-loader',
exclude: /node_modules/
}
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script src="./../dist/bundle.js"></script> </body> </html>
index.ts
import Employee from './employee';
var emp = new Employee();
emp.printName('James');
employee.ts
export default class Employee {
printName(name:string){
console.log(`Hello ${name}`);
}
}