Comprehensive Guide to Using Webpack with TypeScript

Profile picture of Bhavik Bamania
Bhavik Bamania
·6 min read
Working on Webpack with Typescript
Working on Webpack with Typescript

If you're new to TypeScript and web development, you might have heard of Webpack but don’t fully understand what it does. This post will guide you through setting up Webpack with TypeScript, showing how they work together to make your development process smoother. We'll walk you through each step in detail, from installation to configuration, in a way that’s simple and approachable.

Prerequisites

Before we dive in, make sure you have the following tutorials under your belt:

What is Webpack? Why Do We Need It?

Before we start, let’s break down what Webpack does and why it’s such an important tool for modern web development.

Webpack is a module bundler. In simple terms, it takes your different pieces of code (like JavaScript, TypeScript, CSS, and other assets), and bundles them together into one or more files. Why is this necessary?

Imagine you're building a website with dozens of JavaScript and TypeScript files, plus some CSS files and images. Without Webpack, you’d need to manually include all these files in your HTML and manage their dependencies yourself. This can quickly get out of hand as your project grows.

Webpack automates this for you. It figures out how all your files are connected (what files depend on what) and bundles them into a small number of optimized files for you. This way, when a user visits your site, they don’t need to download every single file—they just get the final bundled files, which speeds up page load time.

In summary, Webpack is essential for organizing, optimizing, and delivering your code efficiently, especially when working with TypeScript, which needs to be compiled into JavaScript before it can run in a browser.

Installing Webpack and Important Dependencies

Now that we understand what Webpack is, let’s start setting it up for a TypeScript project.

Step 1: Set Up Your Project

First, create a new folder for your project and initialize it with a package.json file. This will help manage your project’s dependencies.

mkdir typescript-with-webpack
cd typescript-with-webpack
npm init -y

The -y flag tells npm to automatically generate a package.json file with default settings.

Step 2: Install Webpack

To use Webpack, we need to install it, along with webpack-cli, which gives us access to Webpack commands in the terminal.

npm install webpack webpack-cli --save-dev
  • webpack: This is the core Webpack package.
  • webpack-cli: This allows us to use Webpack via the command line.

Step 3: Install TypeScript and ts-loader

Since we are working with TypeScript, we also need to install the TypeScript compiler and ts-loader, which tells Webpack how to handle TypeScript files.

npm install typescript ts-loader --save-dev
  • typescript: The official TypeScript compiler.
  • ts-loader: A Webpack loader that integrates TypeScript with Webpack. It compiles .ts files into JavaScript so that Webpack can bundle them.

Step 4: Install Webpack Dev Server (Optional)

For a better development experience, you can install webpack-dev-server, which automatically reloads the page when your code changes.

npm install webpack-dev-server --save-dev

With this, we’re ready to configure Webpack.

Adding Entry & Output Configuration

Now, we’ll tell Webpack where to start bundling our code (the entry point) and where to save the final bundled file (the output).

Create a webpack.config.js file in the root of your project directory. This file will contain all of Webpack’s configuration settings.

// webpack.config.js
const path = require('path');

module.exports = {
  entry: './src/index.ts', // Entry point for the application
  output: {
    filename: 'bundle.js', // Output filename
    path: path.resolve(__dirname, 'dist') // Directory to save the bundled file
  },
  resolve: {
    extensions: ['.ts', '.js'] // Automatically resolve these extensions
  }
};

Breaking It Down:

  • entry: This is where Webpack starts bundling. We’re telling it to start from src/index.ts. Think of this as the main file that links to all the other files in your app.
  • output: Webpack will bundle all the code into one file, bundle.js, and save it in the dist (short for distribution) folder. This is the file you will reference in your HTML.
  • resolve: This tells Webpack to automatically resolve files with .ts and .js extensions, so you don’t need to specify the extension when importing files in your code.

Adding TypeScript Support with ts-loader

Webpack doesn’t understand TypeScript out of the box, so we need to add the ts-loader to tell Webpack how to handle .ts files.

To do this, we add a module section to our webpack.config.js.

// webpack.config.js
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$/, // Match all TypeScript files
        use: 'ts-loader', // Use ts-loader to compile them
        exclude: /node_modules/ // Exclude node_modules from this rule
      }
    ]
  }
};

Breaking It Down:

  • module.rules: This is where we define how Webpack should handle different file types.
  • test: /\.ts$/: This tells Webpack to apply the rule to any file ending in .ts (TypeScript files).
  • use: 'ts-loader': When Webpack encounters a TypeScript file, it will use ts-loader to compile it into JavaScript.
  • exclude: /node_modules/: We don’t want Webpack to process any files in node_modules, as they are third-party libraries and already compiled.

Adjusting Webpack Config for Development and Production

Now, let's make our Webpack configuration smarter by adjusting it based on the environment—whether we're in development (local coding) or production (ready for users). In development, we want fast builds and source maps for debugging. In production, we want optimized, minified code for faster loading times.

Here’s how we can adjust the Webpack config:

// webpack.config.js
const path = require('path');

module.exports = (env) => {
  const isProduction = env === 'production';

  return {
    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/
        }
      ]
    },
    devtool: isProduction ? false : 'source-map', // Source maps for debugging
    mode: isProduction ? 'production' : 'development', // Set the mode
    devServer: {
      contentBase: path.join(__dirname, 'dist'),
      open: true // Open the browser automatically
    }
  };
};

Breaking It Down:

  • isProduction: We use env to check if we’re in production mode or not. Based on this, we adjust the configuration.
  • devtool: This controls how source maps are generated. Source maps make it easier to debug code by showing the original TypeScript code in your browser's developer tools instead of the bundled JavaScript. We only enable this in development.
  • mode: This tells Webpack whether we are building for development (with faster builds and more debugging features) or production (with optimized code).
  • devServer: This section configures Webpack's development server. When you run the server, it serves your files from the dist folder and automatically reloads the browser whenever you make changes.

Conclusion

You’ve now learned how to set up Webpack to work with TypeScript, ensuring your code is compiled, bundled, and optimized. We’ve covered:

  • What Webpack is and why it's essential for TypeScript projects.
  • Installing the required dependencies.
  • Configuring Webpack to handle TypeScript with ts-loader.
  • Adjusting the config for both development and production environments.

As you progress, you can further optimize your setup, adding plugins for features like minification, CSS handling, and more. Webpack is a powerful tool, and understanding how to configure it for your projects is an essential skill for any modern web developer.

Author of Bhavik Bamania

Written by

Bhavik Bamania