Compiling TypeScript via webpack and babel-loader

[2019-10-12] dev, typescript, webpack, babel
(Ad, please don’t block)

ts-loader has one downside: We can’t pipe the output of another loader into it; it always reads the original file. As a work-around, we can use babel-loader to compile TypeScript. This blog post explains how.

package.json:

{
  ···
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/preset-env": "^7.6.3",
    "@babel/preset-react": "^7.6.3",
    "@babel/preset-typescript": "^7.6.0",
    "babel-loader": "^8.0.6",
    ···
  },
  "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react",
      "@babel/preset-typescript"
    ]   
  }
}

Notes:

  • The order of the presets seems to matter. My setup didn’t work if @babel/env came after @babel/typescript.
  • preset-env: Make sure you get targeted browsers and the inclusion of builtins right (see documentation).
    • For example, if you transpile async functions to JavaScript that doesn’t even use generators, then you need to include the regenerator runtime.

webpack.config.js:

module.exports = {
  ···
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'babel-loader',
      },
      ···
    ],
  },
};