Learn TypeScript

Using Webpack with TypeScript

Using Webpack with TypeScript

In this lesson, we will learn how to use Webpack to bundle and minify a TypeScript app.

Technical requirements

You will need the following installed on your computer for this lesson:

  • Node.js and npm. You can download these from https:/​/​nodejs.​org/​en/​download/​. If you already have these installed, make sure that Node.js is at least version 8.2, and that npm is at least version 5.

  • Code editor such as Visual Studio Code. This can be installed from https:/​/​code.​visualstudio.​com/​.

  • The starter project which can be found here.

  • After the starter project has been downloaded. Open it in a code editor and execute the following command in a Terminal window:

npm install

This will install the project dependencies.

Understanding the need for Webpack.

Webpack is a popular tool that we can use to bundle all our JavaScript code into a single minified file. It is capable of running plugins during the bundling process. This means we can use a Babel plugin to transpile code and an ESLint plugin to check for code quality. So, Webpack allows us to execute a single command to produce the build artifacts in a modern project.

Webpack also has a handy development server capable of serving an HTML, JavaScript, and CSS app.

Adding Webpack to the project.

The starter project is a continuation from the last lesson. The app we are building will add numbers from two inputs together.

A difference to the TypeScript code is that the add function has been extracted into a separate file. This will allow us to experience Webpack bundling code from multiple files.

  • In a Terminal window, let’s install the core webpack library, its command-line interface, and its development server:
npm install --save-dev webpack webpack-cli webpack-dev-server @types/webpack-dev-server
  • We need a webpack plugin, babel-loader, to allow Babel to transpile the TypeScript code into JavaScript. Let’s install this:
npm install --save-dev babel-loader
  • The Webpack configuration file is JavaScript based as standard. However, we can use TypeScript if we install a package called ts-node. Let’s install this:
npm install --save-dev ts-node

Configuring Webpack

Webpack is configured using a file called webpack.config.ts.

  • Let’s create a webpack.config.ts file in the project’s root directory with the following content:
import path from "path";
import { Configuration } from "webpack";
import 'webpack-dev-server';
const config: Configuration = {
entry: "./src/index.ts",
module: {
rules: [
{
test: /\.(ts|js)?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-typescript"],
},
},
},
],
},
resolve: {
extensions: [".ts", ".js"],
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
devServer: {
static: path.join(__dirname, "dist"),
compress: true,
port: 4000,
},
};
export default config;

Here are the critical bits in this configuration file:

  • The entry field tells Webpack where to start looking for modules to bundle. In our project, this is index.ts.
  • The module field tells Webpack how different modules will be treated. Our project is telling Webpack to use the babel-loader plugin to process files with .js and .ts extensions.
  • The resolve.extensions field tells Webpack what file types to look for in which order during module resolution.
  • The output field tells Webpack where to bundle our code. In our project, this is the file called bundle.js in the dist folder.
  • The devServer field configures the Webpack development server. We are telling it that the root of the web server is the dist folder, and to serve files on port 4000.

Creating scripts to run Webpack

We will leverage npm scripts to start our app in development mode and build a production version of our app.

  • Let’s add a scripts section to package.json with the following scripts:
"scripts": {
...
"start": "webpack-dev-server --mode development",
"build": "webpack --mode production"
},
  • Run the following command in a Terminal window to start the app in development mode:
npm start

After a few seconds, the Webpack development server will start.

  • In a browser, browse to http://localhost:4000/.

We’ll see our web app:

App

Great!

Leave the app running.

  • Let’s make a change to the add function in utils.ts to make it do a subtraction:
export function add(a: number, b: number): number {
return a - b;
}

The app will automatically refresh. If the Add button is clicked, our modified code will be executed, and a subtraction will occur:

Modified app

Neat!

  • Stop the Webpack development server by pressing CTRL+C.

Notice that bundle.js hasn't been generated in the dist folder. This is because the Webpack development server bundles the code on the fly and serves it from memory rather than the file system.

  • Run the following command in the Terminal window to produce a production build of our app:
npm run build

A bundle.js file has been generated and placed in the dist folder. This contains minified code from index.ts and utils.ts.

Adding type checking into the Webpack process

  • Rerun the Webpack development server:
npm start
  • Update the add function in utils.ts to the following:
export function add(a: number, b: number): number {
return a + b + c;
}

Webpack successfully processes the update. Unfortunately, Webpack doesn't report a type error. This is because we haven't told Webpack to do any type checking yet.

  • Stop the Webpack development server by pressing CTRL+C.

We can use a package called fork-ts-checker-webpack-plugin to enable the Webpack process to type check the code. This means that Webpack will inform us of any type errors.

  • Let’s install this package in the Terminal Window:
npm install --save-dev fork-ts-checker-webpack-plugin @types/fork-ts-checker-webpack-plugin
  • Add the following into to webpack.config.ts:
...
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
const config: webpack.Configuration = {
...,
plugins: [
new ForkTsCheckerWebpackPlugin({
async: false
}),
],
};

We have set the async option to false so that Webpack waits for the type checking process to finish before it emits any code.

  • Rerun the Webpack development server:
npm start

This time Webpack reports the type error:

Type error

Phew!

  • Resolve the issue with the add function:
export function add(a: number, b: number): number {
return a + b;
}

Webpack automatically reruns and completes successfully.

Summary

Webpack allows TypeScript, Babel, and ESLint to work together, allowing us to develop a modern project. The ForkTsCheckerWebpackPlugin Webpack plugin allows code to be type-checked during the bundling process.

Next up is a quiz to test our knowledge of this module.

Did you find this lesson useful?

Share this lesson on twitter
© 2024 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more