TypeScript vs JavaScript is a debate that often arises among developers. While JavaScript has been the go-to language for web development for many years, TypeScript has gained significant popularity. Understanding the advantages of TypeScript over JavaScript can help make an informed decision when choosing a language for projects. So, let's dive into the world of TypeScript and explore why it has become a powerful contender in the realm of web development.
TypeScript (TS) offers several advantages over JavaScript (JS) that make it a popular choice for many developers:
Overall, TypeScript provides a stronger development experience, catches errors at compile-time, and improves code quality and maintainability. It is particularly beneficial for larger projects or teams, where the benefits of static typing and enhanced tooling support are more pronounced.
To bundle TypeScript with webpack, we’ll need to configure webpack to handle TypeScript files and transpile them into JavaScript. Here's a step-by-step guide on how to do it:
Install the necessary dependencies:
pnpm add -D ts-loader typescript
Create a tsconfig.json
file in the root of the project to configure TypeScript:
{
"compilerOptions": {
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"module": "es6",
"skipLibCheck": true,
"strict": true,
"target": "es6"
}
}
This basic tsconfig.json
file includes the following compiler options:
"esModuleInterop": true
: Enables compatibility with modules that use CommonJS-style exports, allowing the use of import
syntax even with modules originally written with require
syntax."forceConsistentCasingInFileNames": true
: Enforces consistent casing of file names, preventing issues when working with case-sensitive file systems."module": "es6"
: Specifies that the module code generation should be in ES6 style modules, enabling the use of modern module syntax like import
and export
."skipLibCheck": true
: Skips type checking of declaration files (.d.ts
files) from external libraries, which can improve compilation performance."strict": true
: Enables strict type-checking and additional strictness in the TypeScript compiler, helping catch potential errors and enforcing better coding practices."target": "es6"
: Sets the target ECMAScript version for the generated JavaScript code to ES6, allowing the use of modern language features and syntax.These options provide a configuration that enables strict type-checking, interoperability with different module systems, and compatibility with modern ECMAScript features.
To enable TypeScript support in webpack, we'll use the ts-loader
plugin. This plugin allows webpack to handle TypeScript files and perform necessary transpilation.
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { PurgeCSSPlugin } = require('purgecss-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const path = require('path')
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\\.scss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
{
test: /\\.ts$/,
use: 'ts-loader',
},
],
},
optimization: {
minimizer: [new CssMinimizerPlugin(), new TerserPlugin()],
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, '../dist'),
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
}),
new MiniCssExtractPlugin({
filename: 'index.css',
}),
new PurgeCSSPlugin({
paths: ['./src/index.html'],
}),
],
}
Let's convert our src/index.js
file to TypeScript (src/index.ts
) to leverage the benefits of static typing and enhanced tooling provided by TypeScript.
import './index.scss'
const form = document.getElementById('add-form') as HTMLFormElement
const output = document.getElementById('result') as HTMLOutputElement
const foo = 'bar'
function multiply(nums: number[]) {
const result = nums.reduce((acc, num) => acc * num, 1)
return result
}
function sum(nums: number[]) {
const result = nums.reduce((acc, num) => acc + num, 0)
return result
}
form.addEventListener('submit', (e) => {
e.preventDefault()
const first = +(e.target as HTMLFormElement)['first'].value
const second = +(e.target as HTMLFormElement)['second'].value
const result = sum([first, second])
output.innerText = `Total = ${result}`
})
Run the webpack build command.
That's it! We have now set up webpack to bundle TypeScript files.