DEV Community

Vivek Kumar
Vivek Kumar

Posted on

Setup rollup for React Library project - 2024

In this tutorial, we will learn how we can setup our development environment for React Library Project.

I will keep it very simple in steps and will try to explain as much as i can.
I assume you must have node installed and you are already familiar with npm.
Open your terminal in your project folder.

Step 1 - Initializing npm package.

npm init --yes
You can fill rest of things in package.json.

Step 2 - Installing React dependencies

npm i -D react react-dom
Enter fullscreen mode Exit fullscreen mode

Once you will install you can find it in devDependencies in package.json.
But we don't need to bundle react and react-dom in our library considering the consumers will already be having these two.
So, copy react and react-dom to peerDependencies.
By doing this it will be considered external library while bundling.

"devDependencies": {

  },
  "peerDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
Enter fullscreen mode Exit fullscreen mode

Step 3 - Installing rollup

npm i -D rollup
Enter fullscreen mode Exit fullscreen mode

Step 4 - Create a rollup config file in project

Create a file with name rollup.config.js

export default [
 //rollup configurations
]
Enter fullscreen mode Exit fullscreen mode

This is an array because we can add multiple configurations.

Step 5 - Input configuration

So the first thing we need do is let rollup know which file is our entry file.



export default [
    {
        input: './src/index.js',

    }
]
Enter fullscreen mode Exit fullscreen mode

Step 6 - Output Configuration

Next, we will define how our output files will look like and where it will reside.

export default [
    {
        input: './src/index.js',
        output: [
            {
                file: 'dist/index.js',
                format: 'cjs',
                sourcemap: true
            },
            {
                file: 'dist/index.es.js',
                format: 'es',
                exports: 'named',
                sourcemap: true
            }
        ]
    }
]
Enter fullscreen mode Exit fullscreen mode

If you notice, I have added two output files, one in format of commonjs i.e. 'cjs' and another is ES6 i.e. 'es'.

Using two different types of output in the Rollup configuration is a common practice when you want to provide your library in different module formats to cater to various use cases and environments. In this specific configuration:

CommonJS (cjs) Format:
    File: dist/index.js
    Format: cjs (CommonJS)
    Sourcemap: Enabled (sourcemap: true)

CommonJS is a module format commonly used in Node.js environments. This format allows your library to be consumed by Node.js applications or projects that use bundlers compatible with CommonJS.

ECMAScript Module (es) Format:
    File: dist/index.es.js
    Format: es (ECMAScript module)
    Exports: Named exports (exports: 'named')
    Sourcemap: Enabled (sourcemap: true)

ECMAScript module format is the standard for modern JavaScript, and it is widely supported in modern browsers and other environments. Providing your library in this format allows developers to import it directly into projects that support ES modules.
Enter fullscreen mode Exit fullscreen mode

The inclusion of source maps (sourcemap: true) also aids in debugging by mapping the bundled code back to the original source code.

Now since we have defined input and output configurations, the next thing is how we will be transpiling our code from input to output.

Step 7 - Installing Babel

Before we proceed, we will install basic libraries we need to transpile our react code.

npm i -D babel-core babel-loader @babel/preset-react
Enter fullscreen mode Exit fullscreen mode

Step 8 - Installing Rollup plugins

Install these plugins as devDependencies
@rollup/plugin-babel
@rollup/plugin-node-resolve
rollup-plugin-peer-deps-external
@rollup/plugin-commonjs
@rollup/plugin-terser

Step 9 - Configure rollup plugins

import babel from '@rollup/plugin-babel';
import resolve from '@rollup/plugin-node-resolve';
import external from 'rollup-plugin-peer-deps-external';
import commonjs from '@rollup/plugin-commonjs';
import terser from '@rollup/plugin-terser';

export default [
    {
        input: './src/index.js',
        output: [
            {
                file: 'dist/index.js',
                format: 'cjs',
                sourcemap: true
            },
            {
                file: 'dist/index.es.js',
                format: 'es',
                exports: 'named',
                sourcemap: true
            }
        ],
        plugins: [
            external(),
            resolve({ extensions: ['.js', '.jsx'] }),
            commonjs(),
            babel({
                babelHelpers: 'bundled',
                exclude: 'node_modules/**',
                presets: [['@babel/preset-react', { "runtime": "automatic" }]],
                extensions: ['.js', '.jsx']
            }),
            terser()
        ]
    }
]
Enter fullscreen mode Exit fullscreen mode

lets understand line by line
external(): Marks external dependencies to avoid bundling them. External dependencies should be resolved at runtime.
resolve({ extensions: ['.js', '.jsx'] }): Resolves modules using Node.js resolution algorithm, and specifies the allowed file extensions for modules.
commonjs(): Converts CommonJS modules to ES modules, allowing interoperability between CommonJS and ES module formats.
babel({ options }): Transpiles JavaScript code using Babel. In this case, it includes presets for React (@babel/preset-react) with automatic runtime ({ "runtime": "automatic" }).
terser(): Minifies the bundled code using Terser, reducing its size.

What is runtime: "automatic ?

The "automatic" runtime in Babel refers to the new JSX transform introduced in Babel 17. This transform changes how JSX is compiled, and it eliminates the need for a global React import in each file that uses JSX.

In earlier versions of Babel, when you used JSX in your code, Babel would automatically transform it into React.createElement calls. However, this transformation required a reference to the React object, so you had to include import React from 'react' at the top of each file using JSX.

With the introduction of the automatic runtime in Babel 17, the need for the explicit React import is eliminated. Instead of injecting React.createElement calls directly into your code.

This is all you need to get started with rollup for react.

Top comments (2)

Collapse
 
shlomo_moller_570139049f8 profile image
Shlomo Moller

Can you please elaborate on why you chose this solution?
I see there are many ways to use Babel, Webpack, tsup, Rollup, and other tools.
Also, there are tools like Vite and NPX CRA that set up a template out of the box...
Also, does npm have a built in tool to do this (some npm bundle minify etc thing)?

Collapse
 
shlomo_moller_570139049f8 profile image
Shlomo Moller

Thanks! SUPER helpful!