The Ultimate Babel Presets Cheatsheet: Transform Your JavaScript with Confidence

Introduction to Babel Presets

Babel is a powerful JavaScript compiler that transforms modern JavaScript code into backwards-compatible versions that can run in older environments. Babel presets are collections of plugins bundled together to support particular JavaScript features or frameworks. They simplify the Babel configuration process by providing pre-determined sets of transformations rather than requiring users to configure individual plugins.

Core Concepts of Babel Presets

  • Presets: Pre-configured bundles of Babel plugins that transform specific sets of JavaScript features
  • Configuration: Defined in .babelrc, babel.config.json, or within package.json
  • Compilation Process: Source code → Babel (with presets) → Compatible JavaScript output
  • Plugin Ordering: Plugins run before presets; presets run in reverse order (last to first)
  • Customization: Presets accept options to fine-tune their behavior

Setting Up Babel with Presets

  1. Install Babel core and CLI:

    npm install --save-dev @babel/core @babel/cli
    
  2. Install desired preset(s):

    npm install --save-dev @babel/preset-env
    
  3. Create configuration file (.babelrc or babel.config.json):

    {
      "presets": ["@babel/preset-env"]
    }
    
  4. Add build script to package.json:

    "scripts": {
      "build": "babel src -d lib"
    }
    
  5. Run the build process:

    npm run build
    

Essential Babel Presets by Category

Official Presets

PresetPurposeKey Features
@babel/preset-envSmart transpilation based on target environmentsBrowser targeting, polyfill injection, module transformations
@babel/preset-reactReact JSX and Flow syntax supportJSX transformation, automatic runtime injection
@babel/preset-typescriptTypeScript supportTS to JS compilation, type annotation removal
@babel/preset-flowFlow static type checker supportFlow annotation stripping, module exports

Framework-Specific Presets

PresetPurposeKey Features
@vue/babel-preset-appVue.js applicationsJSX, modern syntax, polyfills for Vue CLI
@angular/babel-presetAngular applicationsDecorators, class properties, async/await
@svelte/babel-presetSvelte applicationsComponent compilation, reactive statements
@emotion/babel-preset-css-propEmotion CSS-in-JSCSS prop transformation, styled components

Special Purpose Presets

PresetPurposeKey Features
@babel/preset-modulesES modules optimizationFixed edge cases in modern browsers
babel-preset-minifyCode minificationSize reduction, dead code elimination
babel-preset-power-assertTesting enhancementDetailed assertion messages
babel-preset-gatsbyGatsby.js applicationsReact, flow, TypeScript and class properties

Preset-env Configuration Options

{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "browsers": ["last 2 versions", "not dead", "> 0.5%"],
        "node": "current"
      },
      "useBuiltIns": "usage",
      "corejs": 3,
      "modules": false,
      "debug": true
    }]
  ]
}

Common Challenges and Solutions

ChallengeSolution
Excessive bundle sizeConfigure preset-env with specific targets and useBuiltIns: "usage"
Conflict between presetsEnsure proper preset ordering (most specific last)
Missing polyfillsAdd core-js and configure useBuiltIns option
TypeScript and React togetherUse both presets with proper ordering (typescript before react)
Experimental features not workingAdd specific plugins for cutting-edge features not in presets
Slow build timesUse selective transpilation with browserslistrc or implement caching

Best Practices for Babel Presets

  • Be specific with targets: Define precise browser/node versions to avoid unnecessary transformations
  • Leverage browserslist: Use .browserslistrc for sharing targets across tools
  • Enable debugging: Use debug: true option to see what’s being transformed and why
  • Separate dev and prod configs: Use different settings for development and production
  • Implement caching: Enable the cacheDirectory option for faster rebuilds
  • Keep dependencies updated: Regularly update Babel and its presets for improvements
  • Avoid redundancy: Don’t use plugins already included in your presets
  • Use the minimal configuration: Start simple and add complexity only when needed

Comparison: useBuiltIns Options

OptionEffectBundle SizeWhen to Use
falseNo polyfills includedSmallestWhen using another polyfill strategy
"entry"Replaces import statements with specific polyfillsMediumFor complete environment support
"usage"Adds polyfills based on actual code usageOptimizedMost applications (recommended)

Resources for Further Learning


Would you like me to explain any particular section of this cheatsheet in more detail, or would you like to proceed with another topic for your next cheatsheet?

Scroll to Top