Skip to content
FEE
Frontend Engineering Essentials
Mid Level
Hardened· 2026-07

Transpilation: Babel, TypeScript Compiler & SWC ​

Context ​

Before 2014, writing modern JavaScript meant waiting for browsers to catch up. ECMAScript 2015 (ES6) introduced classes, arrow functions, destructuring, and modules. Browser vendors shipped support on different timelines, and Internet Explorer lagged years behind, so a team's practical choice was to stay on ES5 indefinitely or accept that a share of users would see broken pages.

Babel changed that constraint entirely. By compiling modern JavaScript to an older dialect, it decoupled what you write from what browsers can run. Developers started adopting ES2015+ features the day specifications stabilized rather than waiting two to four years for broad browser support. The phrase "use it now" became a description of how frontend development worked.

Transpilation is source-to-source compilation: the input and output are both human-readable source code, just in different dialects or with different feature sets. This is distinct from compiling to machine code (what Rust or C++ compilers do) or to bytecode (what the JVM or .NET CLR consume). The main transpilation jobs in a modern frontend project are:

  • Syntax lowering — converting async/await, optional chaining, nullish coalescing, and class fields to equivalent ES5 or ES2015 constructs that older runtimes understand.
  • Type stripping — removing TypeScript type annotations so that the output is valid JavaScript a browser or Node can execute.
  • JSX transformation — converting <Component /> to React.createElement(Component, null) or the equivalent automatic runtime call.
  • Polyfill injection — adding runtime implementations, typically from the core-js library, for APIs a target environment lacks (Promise, Array.prototype.flat), since syntax transforms alone cannot add a missing built-in.

These jobs look similar but carry different performance characteristics. Type stripping is essentially a text transformation: once you locate the annotation boundaries, deletion is straightforward. Type checking verifies that user.id is actually a string where you promised one. Answering that requires resolving the import user came from and following inference across file boundaries, not just reading the one file in front of you. That is why modern pipelines run stripping and checking as two separate steps instead of one: a fast one for every file save, and a slower one gated once in CI.

Visual ​

Two-path pipeline for a TypeScript source file in a modern project:

TypeScript source (.ts / .tsx)
         │
         ├─────────────────────────────────────────────────┐
         │                                                 │
         ▼                                                 ▼
  tsc --noEmit                                    SWC / esbuild
  (whole-program)                                 (per-file, parallel)
         │                                                 │
         ▼                                                 ▼
  Type errors                                      JS output (.js)
  (reported in CI)                                 (no types, no JSX)
  pass / fail                                             │
                                                          ▼
                                                    Bundler (Rollup /
                                                    Webpack / esbuild)
                                                          │
                                                          ▼
                                                   Production bundle

The left path runs once per CI job. The right path runs on every file save in development.

Example ​

1. Babel configuration with browserslist ​

.babelrc.json:

json
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "corejs": "3.37"
      }
    ],
    ["@babel/preset-react", { "runtime": "automatic" }],
    "@babel/preset-typescript"
  ]
}

package.json (browserslist field, read by @babel/preset-env automatically):

json
{
  "browserslist": ["> 0.5%", "last 2 versions", "not dead"]
}

useBuiltIns: "usage" paired with corejs: "3.37" tells Babel to scan each file for APIs the target browsers lack (Promise, Array.prototype.flat, and similar) and insert only the matching polyfills from core-js, the polyfill library most of the ecosystem standardizes on, instead of shipping the entire core-js bundle to every page.

@babel/preset-env queries the browserslist database to determine which syntax transforms to apply. Without a browserslist config, it has no target information and defaults to transforming everything, producing larger, slower output than necessary.

@babel/preset-typescript strips TypeScript annotations; it does not type-check. Running tsc --noEmit separately is required to catch type errors.

2. tsconfig.json with annotated key options ​

json
{
  "compilerOptions": {
    // Output dialect. "ES2022" is safe for Node 18+ and modern browsers.
    // When SWC or esbuild handles emit, tsc still reads this for type inference.
    "target": "ES2022",

    // "bundler" (TypeScript 5.0+): models how Vite/Webpack resolve modules.
    // Honors package.json "exports", allows extensionless relative imports.
    // Use "node16" only for Node.js CLIs/libraries that ship without a bundler.
    "moduleResolution": "bundler",

    // Required when moduleResolution is "bundler".
    "module": "ESNext",

    // Enables: strictNullChecks, noImplicitAny, strictFunctionTypes, and more.
    // Start with true on new projects; adding it to existing code requires fixes.
    "strict": true,

    // Path aliases — must match the aliases configured in your bundler as well.
    "paths": {
      "@/*": ["./src/*"]
    },

    // Do not write .js files; tsc is used only for type checking.
    // Remove this flag if tsc is your emit step (rare in bundler-based projects).
    "noEmit": true,

    // Include .tsx files in type checking.
    "jsx": "react-jsx"
  },
  "include": ["src"]
}

3. Next.js: SWC compiler configuration ​

next.config.mjs (Next.js 13+; SWC is already the default, no flag needed):

js
/** @type {import('next').NextConfig} */
const nextConfig = {
  // SWC is the default compiler since Next.js 12.
  // The following options configure SWC-specific transforms.

  compiler: {
    // Remove console.log calls from production builds.
    removeConsole: process.env.NODE_ENV === "production",

    // Enable styled-components support (replaces babel-plugin-styled-components).
    styledComponents: true,
  },

  // If you have a .babelrc, Next.js falls back to Babel automatically.
  // To force SWC even with a .babelrc, there is no override — remove .babelrc.
};

export default nextConfig;

Migrating from Babel to SWC in Next.js: delete .babelrc (or .babelrc.json) and remove babel-loader from devDependencies. Next.js will use SWC on the next next dev or next build invocation. For custom Babel plugins that have no SWC equivalent, keep the .babelrc file. Next.js falls back to Babel per-file.

4. CI command: type check then transpile ​

bash
# Run in CI before building. Exits non-zero on any type error.
pnpm tsc --noEmit

# If tsc passes, use SWC to emit the distributable output.
# -d sets the output directory; --source-maps includes source maps.
pnpm swc src -d dist --source-maps

# Or, in a Next.js project, let the framework orchestrate both:
pnpm tsc --noEmit && pnpm next build

Vite has used esbuild internally for TypeScript transpilation and JS transforms since Vite 2.0 (2021). Vite 8 (2026) replaces that dev-time esbuild step, and Rollup's production bundling, with a single Rust-based bundler, Rolldown, built on the oxc toolchain. Either way, no bundler in this lineage checks types as part of the build, so add tsc --noEmit as a separate step before or after the build, not instead of it:

bash
pnpm tsc --noEmit && pnpm vite build

5. Programmatic SWC via @swc/core ​

js
import { transform } from "@swc/core";

const result = await transform(
  `const greet = (name: string) => \`Hello, \${name}\`;`,
  {
    jsc: {
      parser: { syntax: "typescript" },
      target: "es2020",
    },
    sourceMaps: true,
  }
);

console.log(result.code);
// const greet = (name) => `Hello, ${name}`;

Best Practices ​

SHOULD separate type checking (tsc --noEmit) from transpilation (SWC or esbuild) in CI, and make type checking a required CI step. Type stripping is per-file and parallel; type checking requires whole-program analysis, so a single run costs about as much as checking the entire project. Implementation still matters here: TypeScript 7's native Go compiler cuts that cost by roughly 10x over the previous JavaScript-based tsc (see Design Thinking below). Running SWC for transforms and tsc --noEmit as a blocking CI gate gives you the fastest possible hot path in development while ensuring type errors are caught before merge. The pattern pnpm tsc --noEmit && pnpm vite build is the standard for Vite projects.

SHOULD configure browserslist targets explicitly in every project that uses @babel/preset-env. Without a browserslist configuration, @babel/preset-env has no information about which browsers to target and may apply all transforms (producing unnecessarily large output) or none. Define targets in package.json ("browserslist" field) or a .browserslistrc file and keep them updated as your support matrix evolves.

SHOULD use moduleResolution: "bundler" in tsconfig.json for any project built by Vite, Webpack, or another bundler (TypeScript 5.0+). The node resolution strategy does not understand the package.json exports field, which is used by modern dual-format packages for CJS/ESM selection. Using the wrong resolution mode causes TypeScript to produce false errors for valid bundler-resolved imports. Pair moduleResolution: "bundler" with "module": "ESNext" and "noEmit": true when tsc is used only for type checking.

MUST NOT treat @babel/preset-typescript as a type checker. Babel strips TypeScript annotations without validating them. A file with incorrect type annotations transpiles successfully, producing no errors. Type errors only surface when tsc --noEmit runs across the entire project. Using Babel without a separate tsc step provides zero type-safety guarantees.

SHOULD configure path aliases in both tsconfig.json and the bundler separately: they are independent systems.paths in tsconfig.json satisfies TypeScript's module resolution for type checking, but SWC, esbuild, and Vite each use their own alias configuration. Defining paths in tsconfig alone has no effect on bundler resolution at runtime. MUST configure resolve.alias in Vite (or the equivalent in your bundler) to match every alias in tsconfig.json.

Design Thinking ​

Why Babel was transformative. Before Babel, teams waited two to four years after a feature was standardized before they could ship it: the time it took browser vendors to implement support, and for Internet Explorer's user share to fall below a team's cutoff. Babel cut that wait to days. When TC39 finalized a proposal, a plugin for it typically shipped within the week, and teams used optional chaining and nullish coalescing in production long before every browser supported them natively. Every transpiler that followed, including SWC and esbuild, inherited that assumption: developers now expect a compile step as a normal part of shipping JavaScript.

Why TypeScript won the type-safety war. TypeScript was not the first attempt to add static types to JavaScript. Closure Compiler and Flow both arrived earlier. TypeScript won for three structural reasons. First, its type system is structural rather than nominal: if two types have the same shape, they are compatible. This made adoption gradual: a function that accepts { name: string } works with any object that has a name string property, with no explicit declaration of intent required. Second, TypeScript allowed incremental adoption: a .js file renamed to .ts with no other changes is valid TypeScript. Teams could migrate file by file across months rather than undertaking a full rewrite. Third, the ecosystem aligned: DefinitelyTyped provided type definitions for thousands of npm packages, and major frameworks (React, Vue, Angular) published first-party types. By 2023, TypeScript had become the default starting point for new projects using any of these frameworks.

Why SWC and esbuild replaced Babel for transpilation speed. Babel's bottleneck is the JavaScript runtime. Parsing a file into an AST, traversing that AST through a plugin chain, and printing modified AST nodes back to source code all runs inside V8. V8 is fast for general computation, but AST manipulation is allocation-heavy: each node is an object, and every transform allocates new ones for the garbage collector to eventually clean up. SWC performs the same work in Rust, which compiles to native code with no GC pauses and can process multiple files on separate OS threads simultaneously.

On SWC's own single-file benchmark, SWC transforms roughly 18x faster than Babel on a single thread (616 vs. 34 operations per second; SWC targeting ES3 against Babel targeting ES5, an easier target for Babel) and up to roughly 70x faster once many transforms run concurrently across Node worker threads (2,199 vs. 32 operations per second at 100 concurrent operations). Treat that as an upper bound from a vendor's synthetic single-file benchmark, not a general multiplier your own codebase will see.

esbuild takes the same native-code approach in Go, with a particular focus on parallelism. A third native transpiler, oxc (the JavaScript Oxidation Compiler, written in Rust), has since joined SWC and esbuild; it now provides the parsing and transform layer for Rolldown, the bundler Vite 8 uses by default. All three skip type checking by design: type checking needs to see the whole program at once, and a per-file transpiler only ever looks at the file in front of it. By keeping checking and transpiling separate, you get the fastest possible transform in the hot path (every file save in development) while running the expensive check once in CI.

The tsc --noEmit + SWC pattern, and what TypeScript 7 changes about it. Type checking and transpilation are separate concerns with different performance profiles, and that gap is structural. Checking a single file is not enough: TypeScript has to resolve the imports that file depends on and follow inference across those files before it can trust that user.id really is a string, so a single check costs roughly as much as checking the whole project. Transpilation carries no such requirement: SWC or esbuild can strip and lower one file without ever opening another.

What implementation delivers on top of that structural gap is not fixed. TypeScript 7.0, released in July 2026, replaces the JavaScript-based compiler with a native port written in Go (developed under the code name Project Corsa and distributed for preview as tsgo). On Microsoft's own benchmark, checking the VS Code codebase (about 1.5 million lines) dropped from 77.8 seconds to 7.5 seconds, roughly 10x faster, with no change to what gets checked or how strict the rules are. That resets the calculus in this section: tsc --noEmit in CI is far cheaper on TypeScript 7 than it was on TypeScript 6, and a project that adopted an SWC-only build specifically to dodge a slow tsc step has less reason to now. Whole-program analysis is still required, so checking and transpiling remain separate jobs, but the cost of the checking half just fell by an order of magnitude.

Decoupling the two concerns still lets you assign each to the tool suited for it:

  • In development: SWC transforms files on demand, giving fast Hot Module Replacement (HMR) updates, typically under 100ms per file.
  • In CI: tsc --noEmit runs once across the full project and reports type errors. If it passes, SWC produces the distributable output.

Vite (2.0, February 2021) was among the first major tools to default to this split, transpiling TypeScript per file with esbuild while leaving type checking to the editor or a separate tsc run. Next.js 12 (October 2021) brought the same split to a major React framework, switching its default compiler from Babel to SWC with no required code changes. Per Vercel's release post, that switch delivered about 3x faster Fast Refresh and about 5x faster production builds. A separate figure in the same post, that Rust-based compilation is 17x faster than Babel, measures raw transform throughput and is not a refresh-time number. The presence of a .babelrc file still causes Next.js to fall back to Babel automatically, preserving compatibility for projects with custom Babel plugins.

Why moduleResolution: "bundler" exists. TypeScript's node resolution mode models how require() works in Node.js: given import x from './foo', it tries ./foo.js, then ./foo/index.js, then falls back to the main field in foo's package.json. Bundlers like Vite and Webpack resolve differently. They honor the exports field in package.json, which node resolution ignores entirely, and that field is how most modern dual-format packages advertise separate ESM and CJS entry points. Using moduleResolution: "node16" or "node" in a Vite project causes TypeScript to emit false errors for imports that resolve correctly at build time, because the type checker is applying rules the bundler does not follow. TypeScript 5.0 introduced moduleResolution: "bundler" to close that gap: it consults the exports field the way a bundler does, so type checking and bundling agree on which files a given import actually resolves to.

Deep Dive ​

Runtime-level type stripping ​

Everything above assumes a build step runs before the browser or Node.js loads your code, turning .ts into .js. That assumption has weakened for backend and tooling code. Node.js added experimental support for running .ts files directly in v22, made it available without a flag in v23.6 (January 2025), and ships it enabled by default in v24, the LTS line as of 2026. Internally, Node uses a module called amaro, a wrapper around @swc/wasm-typescript (a WebAssembly build of SWC's TypeScript parser), to remove type annotations and replace them with matching whitespace so that stack traces still point at the correct line. There is no type-checking step: Node runs .ts files that use only erasable syntax and errors on constructs a type checker would need to resolve, such as enum declarations and namespaces that emit runtime code.

Bun and Deno have run TypeScript directly since their first releases, using their own bundled transpilers rather than Node's amaro. Between Node 24's default stripping and Bun and Deno's native TypeScript execution, a growing share of backend and tooling code needs no separate transpile step before it runs. None of this replaces tsc --noEmit for catching type errors; it only removes the step that used to be required to make a .ts file valid JavaScript in the first place, and it does not apply to frontend code, which still ships to browsers that only understand JavaScript.

Failure Modes ​

Beyond the configuration mistakes covered in Best Practices, a few failures only surface once a project is actually split across tsc, SWC or esbuild, and a bundler, each reading the same source file under different rules.

Keeping a .babelrc in a Next.js project unnecessarily. A .babelrc causes Next.js to disable SWC entirely and revert to Babel for all files, not just the files that need the custom plugin. If only one plugin is needed, evaluate whether an SWC plugin or a Next.js built-in compiler option provides the same functionality before paying the full Babel performance cost.

const enum and runtime namespaces break silently under SWC and esbuild.tsc inlines a const enum's values at every usage site by looking up the enum's declaration, which can live in a different file than the import. SWC and esbuild transpile one file at a time and never see that declaration, so they emit a plain object instead of inlining it, producing different runtime output than a tsc-only build would. Set isolatedModules: true in tsconfig.json so TypeScript itself flags const enum usage and other constructs, like runtime namespace merging, that don't survive per-file compilation, and avoid them in code that ships through SWC or esbuild.

Type-only imports get erased inconsistently without verbatimModuleSyntax. When a file imports both a type and a value from the same module, TypeScript's default settings sometimes elide the import if it looks type-only and sometimes don't, depending on isolatedModules and how the import is written. A per-file transpiler like SWC only sees the import statement and has to guess whether it survives at runtime; a wrong guess has historically caused "cannot find module" errors and silently dropped values. Set verbatimModuleSyntax: true (TypeScript 5.0+) and write explicit import type { Foo } from "./types" syntax so every tool in the pipeline reads the same intent instead of inferring it independently.

Decorator metadata differs between SWC and tsc. Libraries that rely on emitDecoratorMetadata, commonly dependency-injection frameworks that read a parameter's design-time type at runtime, depend on the compiler emitting that metadata alongside the decorator transform. tsc supports this fully. SWC's decorator support has historically covered the decorator transform itself without matching tsc's full metadata emission, so decorator-based code that works under tsc can fail with missing or generic Object metadata under SWC. Check SWC's current documentation for known gaps in decorator metadata support before moving a decorator-heavy project off tsc-based emit.

Source maps drift when checking and emitting run through different tools.tsc --noEmit produces no output, so it contributes nothing to source maps; whichever tool actually emits code (SWC, esbuild, or Babel) generates its own map independently. If that tool runs on a different intermediate form than the original source, for example a Babel-transformed file instead of the raw .ts, a production stack trace can point at the wrong line. After any change to which tool performs the final emit, verify source maps by throwing an error on a known line and confirming the browser or error tracker points at that same line.

  • FEE-800 — Build Tooling Overview: the broader landscape of build tools this fits into.
  • FEE-801 — Bundlers (Webpack, Rollup, esbuild): how bundlers invoke transpilers internally.
  • FEE-307 — ES Modules: the module format that moduleResolution: "bundler" is designed for.
  • FEE-804 — package.json Fields: exports, main, module — fields that moduleResolution: "bundler" consults.

References ​