DEV Community

Marcin Wosinek
Marcin Wosinek

Posted on • Edited on

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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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"],
      },
    ],
  },
};
Enter fullscreen mode Exit fullscreen mode

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/**/*"]
}
Enter fullscreen mode Exit fullscreen mode

Dependencies

All dependencies that we need to install:

$ npm install --save-dev webpack ts-loader typescript
Enter fullscreen mode Exit fullscreen mode

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

The working example page:
https://marcin-wosinek.github.io/webpack-ts/

Top comments (0)