Guide to setting up Typescript with Webpack

November 13, 2020

This is an easy guide to converting your current webpack/JS/babel configuration to start to use Typescript

This config will also use babel.

If you need to start by installing webpack and getting the basics (before setting up babel) installed then checkout my guide to setting up Webpack - then come back here to continue and install typescript.

(You will also need to install Babel, so also follow the very short guide to setting up Webpack with Babel here)

Installing required packages to run typescript

Run the following command to get starting in converting your webpack configuration to use typescript. This includes installing typescript itself.

yarn add -D source-map-loader ts-loader typescript

Create a .tsconfig.json file

Create a .tsconfig.json file in your root directory, and paste the following in:

{
  "compilerOptions": {
    "outDir": "./dist",
    "allowJs": true,
    "target": "es5"
  },
  "include": ["./src/**/*"]
}

This assumes that your JS files are in /src/.

Update your webpack.config.js file to work with Typescript loaders

const path = require('path');

module.exports = {
  entry: './src/app.js',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {test: /\.tsx?$/,
        use: [
          {
            loader: 'babel-loader',
          },
          {
            loader: 'ts-loader'
          }
        ]
      },

      {test: /\.js$/, loader: 'source-map-loader'},
    ],
  },
};

You should now be able to compile your TS into JS, via webpack and babel!

If you would like to set up TS with Vue 3 check out my guide to setting up Vue 3 with Typescript here