JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstooling
PrevNext
tooling
senior
transpilation

How does Babel work and how do you configure it?

babel
transpilation
presets
plugins
Quick Answer

Babel transforms modern JavaScript to compatible versions using plugins (individual transforms) and presets (plugin collections). Configure via babel.config.js with presets like @babel/preset-env for automatic browser targeting and plugins for specific features.

Detailed Explanation

Babel Pipeline:

  1. Parse code to AST
  2. Transform AST with plugins
  3. Generate output code

Configuration:

  • presets: Collections of plugins
  • plugins: Individual transforms
  • targets: Browser/Node targets
  • env: Environment-specific config

Common Presets:

  • @babel/preset-env: Modern JS
  • @babel/preset-react: JSX
  • @babel/preset-typescript: TS

Key Concepts:

  • Polyfills: Runtime features
  • core-js: Polyfill library
  • useBuiltIns: Polyfill injection

Code Examples

Babel configuration
// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', {
      // Target browsers
      targets: {
        browsers: ['>0.25%', 'not dead'],
        // Or use browserslist in package.json
      },
      // Polyfill configuration
      useBuiltIns: 'usage', // Auto-inject needed polyfills
      corejs: 3,
      // Module output
      modules: false, // Keep ES modules for tree shaking
    }],
    ['@babel/preset-react', {
      runtime: 'automatic', // React 17+ JSX transform
    }],
    '@babel/preset-typescript',
  ],
  plugins: [
    // Decorators (Stage 3)
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    // Class properties
    '@babel/plugin-proposal-class-properties',
    // Optional chaining (if not in preset-env targets)
    '@babel/plugin-proposal-optional-chaining',
  ],
  env: {
    test: {
      presets: [
        ['@babel/preset-env', { targets: { node: 'current' } }],
      ],
    },
    production: {
      plugins: [
        'transform-remove-console',
      ],
    },
  },
};

Resources

Babel Documentation

docs

Babel Plugin Handbook

docs

Related Questions

How does Webpack work and what are its core concepts?

mid
bundlers

How do you configure TypeScript for a project?

mid
typescript
Previous
How do you create custom ESLint rules and plugins?
Next
How do you containerize a JavaScript application with Docker?