DEV Community

Marcin Wosinek
Marcin Wosinek

Posted on • Updated 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>

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

Enter fullscreen mode Exit fullscreen mode


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


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



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:

Top comments (0)