Enhance Your Rollup Workflow with rollup-plugin-babel

Introduction to rollup-plugin-babel

The rollup-plugin-babel is an essential tool for developers who use Rollup as their module bundler and want to utilize Babel to transpile modern JavaScript and React code. This plugin allows you to transform ES6+ code into backwards-compatible JavaScript, enabling better browser support and cleaner, more maintainable code.

Basic Usage

To get started, first install the necessary packages:

npm install --save-dev rollup-plugin-babel @babel/core @babel/preset-env

Then, update your Rollup configuration file to include the Babel plugin:

 import babel from 'rollup-plugin-babel';
export default {
  input: 'src/main.js',
  output: {
    file: 'dist/bundle.js',
    format: 'cjs',
  },
  plugins: [
    babel({
      exclude: 'node_modules/**',
    }),
  ],
}; 

Using Babel Presets

Most users will want to use one or more of Babel’s presets. The @babel/preset-env preset is a great starting point:

 babel({
  presets: ['@babel/preset-env']
}) 

Working with React

If you’re working with React, make sure to include the @babel/preset-react preset:

 npm install --save-dev @babel/preset-react 
 babel({
  presets: ['@babel/preset-env', '@babel/preset-react']
}) 

Plugin Options

The rollup-plugin-babel supports various options that you can pass to the Babel plugin. Here are some common configurations:

Exclude Node Modules

 babel({
  exclude: 'node_modules/**'
}) 

Include Only Specific Files

 babel({
  include: 'src/**'
}) 

Custom Babel Configuration

You can also specify a custom Babel configuration:

 babel({
  babelrc: false,
  presets: ['@babel/preset-env'],
  plugins: ['@babel/plugin-transform-runtime']
}) 

Complete Example

Below is a complete example of using rollup-plugin-babel in a simple React application setup:

 // Install necessary dependencies npm install --save-dev rollup rollup-plugin-babel @babel/core @babel/preset-env @babel/preset-react react react-dom
// rollup.config.js import babel from 'rollup-plugin-babel';
export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'cjs',
  },
  plugins: [
    babel({
      exclude: 'node_modules/**',
      presets: ['@babel/preset-env', '@babel/preset-react']
    }),
  ],
};
// src/index.js import React from 'react'; import { render } from 'react-dom';
const App = () => 

Hello, World!

; render(, document.getElementById('root'));

With rollup-plugin-babel, you can effortlessly integrate Babel into your Rollup-based projects, ensuring your code remains modern, efficient, and compatible with a wide range of environments.

Hash: 4998068beea11326c8fcdf4fd2e4ccbe0ae596236803f3bd68d8caaf269b9d41

Leave a Reply

Your email address will not be published. Required fields are marked *