How Webpack and ESBuild speed up your Typescript build process.

Lukas Gamper
2 min readMar 22, 2021
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.

Using ESBuild to transpile Typescript

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'
+ }
},
...
],
},
}

Add type checking

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(),
...
],
}

Using ESBuild to minify your bundle

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:

ESBuild caveats

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.

Conclusion

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.

--

--