乐闻世界logo
搜索文章和话题

What is the difference between preset and plugin in Babel and how to configure them

3月7日 19:38

Difference Between Preset and Plugin

Plugin

  • Finer granularity: Each plugin handles a single transformation
  • Single purpose: e.g., @babel/plugin-transform-arrow-functions only transforms arrow functions
  • On-demand: Precise control over which transformations are needed

Preset

  • Plugin collection: A group of plugins to simplify configuration
  • Batch processing: Configure once, includes multiple related plugins
  • Common presets:
    • @babel/preset-env: Automatically selects transformations based on target environment
    • @babel/preset-react: React/JSX transformation
    • @babel/preset-typescript: TypeScript transformation

Configuration Methods

1. Using Plugins

javascript
// babel.config.js module.exports = { plugins: [ '@babel/plugin-transform-arrow-functions', '@babel/plugin-transform-classes', // Plugin with options ['@babel/plugin-transform-runtime', { corejs: 3 }] ] };

2. Using Presets

javascript
// babel.config.js module.exports = { presets: [ ['@babel/preset-env', { targets: { browsers: ['> 1%', 'last 2 versions'] }, useBuiltIns: 'usage', corejs: 3 }], '@babel/preset-react' ] };

3. Execution Order

Important rules:

  1. Plugins execute before presets
  2. Plugins execute in order (first to last)
  3. Presets execute in reverse order (last to first)
javascript
module.exports = { plugins: [ 'plugin-a', // Executes 1st 'plugin-b' // Executes 2nd ], presets: [ 'preset-b', // Executes 4th (presets in reverse) 'preset-a' // Executes 3rd ] };

Best Practices

1. Prioritize @babel/preset-env

javascript
module.exports = { presets: [ ['@babel/preset-env', { targets: '> 0.25%, not dead' }] ] };

2. Develop Custom Plugins

javascript
// Simple Babel plugin example module.exports = function(babel) { const { types: t } = babel; return { name: 'my-custom-plugin', visitor: { Identifier(path) { // Transformation logic } } }; };

3. Develop Custom Presets

javascript
// Custom preset module.exports = function() { return { plugins: [ 'plugin-a', 'plugin-b' ] }; };
标签:Babel