How to Bundle up JavaScript Files using Rollup.js?


In this tutorial, we will understand how to use rollup.js to bundle JavaScript files. Before we do that, the first step is to get familiar with the JavaScript module bundler called Rollup, which compiles the files of multiple sources into a single bundle. Rollup is similar to webpack and Browserify. It is more popular than many of the other bundlers out there because of its ability to keep the files small even after bundling them into a single unit.

There are multiple features that Rollup brings to the table, some of them are mentioned below −

  • Development is easier to manage when you are making use of smaller and self-contained source files.

  • The source code can easily be prettified, linted and its syntax checking can be done during the bundling itself.

  • Tree-shaking also helps in removing the unused functions.

  • We can even transpile to ES5 for backward compatibility.

  • Can also have the logging removed and even the production bundles can be minified as well.

Now that we have a fair idea of what Rollup is all about, let's first create a simple JavaScript project.

Suppose we have a project called "rest-api-example" and its directory structure looks something like this −

├── controller
│  └── books.js
├── package-lock.json
├── package.json
├── routes
   └── books.js
└── src
   ├── index.js

3 directories, 5 files

We can see that we have multiple files and directories, and the only file that we need to focus on is the "index.js" file that is present inside the "src" directory.

index.js

This index.js file is the file that we will try to bundle with the help of Rollup.js in different formats. The code of the index.js file is shown below.

// to require the framework
const app = require('fastify')({
   logger: true
})

app.addHook('onRoute', (routeOptions) => {
   console.log(`Routes that are registered are: ${routeOptions.url}`)
})

// to declare a single route
app.get('/', function (req, reply) {
   reply.send({
      Welcome: 'TutorialsPoint'
   })
})

// Register routes to handle blog posts
const bookRoutes = require('../routes/books')
bookRoutes.forEach((route, index) => {
   app.route(route)
})

// Run the server!
app.listen(3000, (err, address) => {
   if (err) {
      app.log.error(err)
      process.exit(1)
   }
   app.log.info(`The server is listening on ${address}`)
})

In this code, we can see that we have used the common JavaScript arrow functions and basic syntax.

Install Rollup as a Dependency

Let's say that we want to bundle this JavaScript file with the help of Rollup.js. In order to do that, we first need to have Rollup installed as a dependency in our project.

The following command will install Rollup in your project.

npm install --save-dev rollup

package.json

Once we run the above command, we should see the rollup dependency in our "package.json" file. The content of my project's "package.json" file is shown below for reference.

{
   "name": "fastify-rest-api",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
      "test": "echo "Error: no test specified" && exit 1"
   },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "dependencies": {
      "fastify": "^4.2.1"
   },
   "devDependencies": {
      "rollup": "^2.77.0"
   }
}

rollup.config.js

With Rollup installed, the next step is to create a new file in the same root location where our "package.json" is present and name that file rollup.config.js.

Note − The exact name should be given to the Rollup config file.

The code snippet shown below is my rollup.config.js file.

export default {
   input: 'src/index.js',
   output: {
      file: 'src/main.min.js',
      : 'cjs',
   }
};

In the above code snippet, we have use different properties. Let me explain each of them in detail.

  • Input − In this field, we provide the name of the file that we want to Rollup. In most of the cases, this file would be the main JavaScript file, that basically starts your project.

  • Output − The output object used in the above config.js file contains two properties, namely, file and format, where the file contains the name of the file that will be created as the output of the rollup, and the format field contains the format type as the value that we want for the rollup.

In our config.js, we are simply saying that we want to have a "cjs" file as output when the Rollup is complete.

Starting Rollup.js

In order to actually start the Rollup and test the same, we need to run the following command in the terminal.

./node_modules/.bin/rollup -c

Once we run the above command, we will get the following output in the terminal.

src/index.js → src/main.min.js...
created src/main.min.js in 13ms

Note that the time of compilation will vary from machine to machine. Now, if we check our directory tree, it should look something like this.

├── controller
│  └── books.js
├── package-lock.json
├── package.json
├── rollup.config.js
├── routes
│  └── books.js
└── src
   ├── index.js
   └── main.min.js

main.min.js

In the above tree structure, we can see that a new file named "main.min.js" is created. Open the file and it should look exactly same as the file shown below.

'use strict';

// to require the framework
const app = require('fastify')({
   logger: true
});

app.addHook('onRoute', (routeOptions) => {
   console.log(`Routes that are registered are: ${routeOptions.url}`);
});

// to declare a single route
app.get('/', function (req, reply) {
   reply.send({
      Welcome: 'TutorialsPoint'
   });
});

// Register routes to handle blog posts
const bookRoutes = require('../routes/books');
bookRoutes.forEach((route, index) => {
   app.route(route);
});

// Run the server!
app.listen(3000, (err, address) => {
   if (err) {
      app.log.error(err);
      process.exit(1);
   }
   app.log.info(`The server is listening on ${address}`);
});

You can easily notice the difference between the size of the file, before and after Rollup.

In the previous example, we roll up to the common JavaScript format, as we mention it inside the format property of the output object inside the rollup.config.js file.

Let's say that we want to make the bundled up JS to be of iife format. For that, we can change the format in the rollup.config.js file.

rollup.config.js

Consider the updated rollup.config.js file shown below.

export default {
   input: 'src/index.js',
   output: {
      file: 'src/main.min.js',
      format: 'iife',
   }
};

Note we just needed to change the value of the format field in the rollup.config.js file and we are all set.

In order to actually bundle up the file, we need to run the command shown below:

./node_modules/.bin/rollup -c

Output

Once we run the above command, we will get the following output in the terminal −

src/index.js → src/main.min.js...
created src/main.min.js in 16ms

Now if we open the " main.min.js" file, it will be in IIFE format.

(function () {
   'use strict';

   // to require the framework
   const app = require('fastify')({
      logger: true
   });

   app.addHook('onRoute', (routeOptions) => {
      console.log(`Routes that are registered are: ${routeOptions.url}`);
   });

   // to declare a single route
   app.get('/', function (req, reply) {
      reply.send({
         Welcome: 'TutorialsPoint'
      });
   });

   // Register routes to handle blog posts
   const bookRoutes = require('../routes/books');

   bookRoutes.forEach((route, index) => {
      app.route(route);
   });

   // Run the server!
   app.listen(3000, (err, address) => {
      if (err) {
         app.log.error(err);
         process.exit(1);
      }
      app.log.info(`The server is listening on ${address}`);
   });
})();

It can be clearly seen that the file is in the IIFE format.

Conclusion

In this tutorial, we learned how we can bundle the JavaScript files with the help of Rollup.js into smaller sizes and into formats of our preferences.

Updated on: 22-Jun-2023

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements