How Webpack and ESBuild speed up your Typescript build process.

Photo by CHUTTERSNAP on Unsplash

ESBuild is the cool new kid in the TypeScript family! It is a JavaScript bundler written in Go which supports blazing fast ESNext & TypeScript transpilation and minification.

The esbuild-loader is a drop in replacement for ts-loader. After installing esbuild-loader with

npm i -D esbuild-loader

update the Webpack config to replace the ts-loader with esbuild-loader:

module.exports = {
module: {
rules: [
{
test: /\.ts$/,
- loader: 'ts-loader',
- options: {
- transpileOnly: true
- }
+ loader: 'esbuild-loader',
+ options: {
+ loader: 'ts', // also 'tsx' is supported
+ target: 'es2016'
+ }
},
...
],
},
}

ESBuild has built-in support for parsing TypeScript syntax, but it discards the type annotations. This means ESBuild does not do any type checking, we need to add the type checking on our own. The Fork TS Checker Webpack Plugin is the perfect candidate.

You probably already use the Fork TS Checker Webpack Plugin, if not add it to your package.json with

npm i -D fork-ts-checker-webpack-plugin

and your update the Webpack config

module.exports = {
plugins: [
new ForkTsCheckerWebpackPlugin(),
...
],
}

The ESBuild-loader also provides a wrapper for the ESBuild minifyer:

module.exports = {
optimization: {
minimizer: [
- new TerserPlugin()
+ new ESBuildMinifyPlugin({
+ target: 'es2016'
+ })
]
}

Congratulations! Now you have a blazing fast developer experience and an extensive type check in the background. For completeness, the full Webpack config:

Features that need a type system are not supported by ESBuild:

  • The TypeScript option emitDecoratorMetadata is not supported. Since ESBuild does not replicate TypeScript's type system, it does not have enough information to implement this feature.
  • const enum types are not supported, since ESBuild compiles each file independently. You should enable the isolatedModules option to catch errors like this, already in the IDE.
  • If you have modules with side effects like Angular style injectables, set theimportsNotUsedAsValues option to preserve. It makes sure, ESBuild does not remove unused imports by tree shaking. You can use import type to avoid circular include cycles.

For a full ist of possible problems see the ESBuild documentation.

ESBuild is an awsome tool to bring your developer experience to the next level. With esbuild-loader minimal effort is required to speed up your existing stack.

How about you? What are your experience with ESBuild? Share your thoughts with me down below.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store