typescript
/

TypeScript Build – Compilation & Build Tools

Last Sync: Today

On this page

12
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Build – Compilation & Build Tools

TypeScript Build Overview

Building TypeScript projects involves compiling TS to JavaScript, bundling modules, optimizing output, and generating source maps. Choose the right tool based on your project needs: speed, features, or ecosystem compatibility.

Using tsc (TypeScript Compiler)

BASHRead-only
1
# Basic compilation
tsc

# Watch mode
tsc --watch

# Build with config
tsc --project tsconfig.json

# Output declaration files
tsc --declaration

# Source maps
tsc --sourceMap
JSONRead-only
1
// tsconfig.json for builds
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "lib": ["ES2020"],
    "outDir": "./dist",
    "rootDir": "./src",
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "removeComments": true,
    "noEmitOnError": true,
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist", "**/*.test.ts"]
}

Webpack + TypeScript

BASHRead-only
1
# Install dependencies
npm install --save-dev webpack webpack-cli ts-loader typescript
npm install --save-dev html-webpack-plugin webpack-dev-server
JavaScriptRead-only
1
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'production',
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js',
    clean: true,
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
  ],
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
};

esbuild – Fastest Builder

BASHRead-only
1
# Install esbuild
npm install --save-dev esbuild

# Build from command line
npx esbuild src/index.ts --bundle --outfile=dist/bundle.js --minify --sourcemap

# Watch mode
npx esbuild src/index.ts --bundle --outfile=dist/bundle.js --watch
JavaScriptRead-only
1
// build.js
const esbuild = require('esbuild');

async function build() {
  await esbuild.build({
    entryPoints: ['src/index.ts'],
    bundle: true,
    outfile: 'dist/bundle.js',
    minify: true,
    sourcemap: true,
    target: ['es2020'],
    platform: 'browser',
    format: 'esm',
    external: [],
  });
  console.log('Build complete!');
}

build();

SWC (Speedy Web Compiler)

BASHRead-only
1
# Install SWC
npm install --save-dev @swc/cli @swc/core

# Compile with SWC
npx swc src -d dist

# Watch mode
npx swc src -d dist -w
JSONRead-only
1
// .swcrc
{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": false,
      "decorators": true
    },
    "target": "es2020",
    "loose": false,
    "minify": {
      "compress": true,
      "mangle": true
    }
  },
  "module": {
    "type": "commonjs"
  },
  "sourceMaps": true,
  "minify": true
}

Vite – Modern Frontend Build

BASHRead-only
1
# Create Vite project
npm create vite@latest my-app -- --template typescript
cd my-app
npm install

# Build for production
npm run build

# Preview build
npm run preview
TypeScriptRead-only
1
// vite.config.ts
import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    outDir: 'dist',
    sourcemap: true,
    minify: 'esbuild',
    rollupOptions: {
      input: {
        main: 'index.html',
      },
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
        },
      },
    },
  },
  server: {
    port: 3000,
    open: true,
  },
});

Build Tool Comparison

ToolSpeedConfig ComplexityBest For
tscSlowSimpleNode.js, libraries
WebpackMediumComplexComplex SPAs, legacy
esbuildVery FastSimpleFast builds, modern apps
SWCVery FastSimpleRust-based compilation
ViteFastSimpleModern SPAs, HMR
ParcelMediumZero-configQuick prototypes

Multi-Target Builds

JSONRead-only
1
// tsconfig.build.json - Base config
{
  "compilerOptions": {
    "strict": true,
    "esModuleInterop": true
  }
}

// tsconfig.esm.json
{
  "extends": "./tsconfig.build.json",
  "compilerOptions": {
    "module": "ESNext",
    "outDir": "./dist/esm"
  }
}

// tsconfig.cjs.json
{
  "extends": "./tsconfig.build.json",
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "./dist/cjs"
  }
}
JSONRead-only
1
// package.json exports
{
  "main": "./dist/cjs/index.js",
  "module": "./dist/esm/index.js",
  "types": "./dist/types/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/esm/index.js",
      "require": "./dist/cjs/index.js",
      "types": "./dist/types/index.d.ts"
    }
  }
}

Optimizing Build Performance

  • Use incremental builds – tsc --incremental or incremental: true
  • Enable skipLibCheck – Skips type checking of declaration files
  • Use project references – Split code into smaller projects
  • Parallel builds – Run tsc --build with composite projects
  • Cache node_modules – In CI pipelines
  • Use faster transpilers – esbuild or SWC for large projects

Production Build Checklist

JSONRead-only
1
{
  "scripts": {
    "build": "npm run clean && npm run compile && npm run bundle",
    "clean": "rm -rf dist",
    "compile": "tsc",
    "bundle": "esbuild dist/index.js --bundle --minify --outfile=dist/bundle.js",
    "type-check": "tsc --noEmit",
    "build:prod": "NODE_ENV=production npm run build"
  }
}

Common Build Issues & Solutions

IssueSolution
Out of memoryIncrease Node memory: NODE_OPTIONS=--max-old-space-size=4096
Slow buildsUse incremental: true and skipLibCheck
Declaration file conflictsUse consistent typesVersions in package.json
Path resolution errorsSet baseUrl and paths in tsconfig.json
Circular dependenciesUse circular-dependency-plugin or madge

Conclusion

Choose your TypeScript build tool based on project requirements. Use tsc for simplicity, esbuild/SWC for speed, Webpack for complex SPAs, or Vite for modern frontend development. Optimize builds with incremental compilation, caching, and proper configuration.

Try it yourself

// Build tool comparison example

// This code would be processed differently by each tool

interface BuildConfig {
  name: string;
  speed: 'fast' | 'medium' | 'slow';
  output: string;
}

const configs: BuildConfig[] = [
  { name: 'tsc', speed: 'slow', output: 'dist/' },
  { name: 'esbuild', speed: 'fast', output: 'dist/' },
  { name: 'swc', speed: 'fast', output: 'dist/' },
  { name: 'webpack', speed: 'medium', output: 'dist/' },
];

function buildProject(config: BuildConfig): Promise<string> {
  console.log(`Building with ${config.name} (${config.speed})...`);
  return Promise.resolve(`Output: ${config.output}`);
}

// Simulate build process
Promise.all(configs.map(buildProject)).then(results => {
  console.log('\nAll builds completed!');
  results.forEach(result => console.log(result));
});

// Export for module builds
export { BuildConfig, buildProject };

Test Your Knowledge

Q1
of 4

Which build tool is fastest for TypeScript compilation?

A
tsc
B
Webpack
C
esbuild
D
Babel
Q2
of 4

What flag generates declaration files?

A
--types
B
--declaration
C
--emit
D
--dts
Q3
of 4

Which tool is known for zero-configuration builds?

A
Webpack
B
esbuild
C
Parcel
D
Rollup
Q4
of 4

How to enable incremental compilation in tsc?

A
--cache
B
--fast
C
--incremental
D
--watch

Frequently Asked Questions

tsc vs esbuild?

tsc does full type checking; esbuild is faster but skips type checking. Use both: tsc for types, esbuild for transpilation.

How to speed up TypeScript builds?

Use incremental builds, skipLibCheck, project references, or faster transpilers like esbuild/SWC.

What are declaration files?

.d.ts files that provide type information for JavaScript code, generated with --declaration flag.

Webpack vs Vite?

Vite is faster for development with HMR; Webpack is more mature with extensive plugin ecosystem.

Previous

ts config

Next

ts linting

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.