Minimal webpack configuration to build typescript

Let's take a look on a minimal webpack configuration needed to build typescript.

Demo page

index.html loads the js from the default webpack output location

<!DOCTYPE html>

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Webpack ts example</title>
    <link rel="shortcut icon" href="#" />
  </head>
  <body>
    <script type="text/javascript" src="dist/main.js"></script>
  </body>
</html>

The demo code is in src/index.ts - a file that is loaded for the default entry point. The code is simple:

const element = document.createElement("div");

element.innerHTML = "hello world!";

document.body.append(element);

Configuration

For this to work, we need 2 configuration files.

Webpack configuration goes to webpack.config.js:

module.exports = {
  resolve: {
    extensions: [".ts", ".js"],
  },
  module: {
    rules: [
      {
        test: /\.ts$/i,
        use: ["ts-loader"],
      },
    ],
  },
};

extensions: [".ts", ".js"] make webpack attempt to load ts when extension is missing, and makes it try TS before JS. Object added to module.rules[] sets ts-loader for all files that ends .ts.

The ts configuration is in tsconfig.json:

{
  "include": ["src/**/*"]
}

Dependencies

All dependencies that we need to install:

$ npm install --save-dev webpack ts-loader typescript

This could work would without installing typescript explicitly - but it's better idea to specify the dependency ourselves & keep it simple to pin the version if ever we will want to it.

Running code

Links

Summary

In this article we have seen to what's the minimal webpack configuration to build ts files. If you want to play with the code, you can find the repo here:

GitHub logo marcin-wosinek / webpack-ts

Minimal configuration to build typescript with webpack

23