Home >Web Front-end >JS Tutorial >An Introduction to the Rollup.js JavaScript Bundler

An Introduction to the Rollup.js JavaScript Bundler

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-02-10 16:01:10631browse

Rollup.js: A Next-Generation JavaScript Module Bundler

An Introduction to the Rollup.js JavaScript Bundler

Rollup.js, created by Rich Harris (also the author of Svelte), is a modern JavaScript module bundler that excels at compiling multiple source files into a single optimized bundle. Unlike some all-in-one bundlers, Rollup focuses primarily on JavaScript, offering speed and customization advantages. Let's explore its key features and how to use it effectively.

Advantages of Using Rollup.js:

  • Simplified Development: Managing smaller, self-contained source files significantly improves development workflow.
  • Enhanced Code Quality: Integrates seamlessly with linters, formatters, and syntax checkers during the build process.
  • Tree-shaking Optimization: Intelligently removes unused code, resulting in smaller and faster bundles.
  • Backward Compatibility: Transpiles modern JavaScript (ES6 ) to ES5, ensuring broader browser support.
  • Flexible Output: Generates multiple output formats (ES5, ES6 modules, CommonJS) to suit various project needs.
  • Performance: Generally faster and more customizable than other bundlers, especially with complex configurations.

Installation:

Rollup.js requires Node.js v8.0.0 or later. You can install it globally:

<code class="language-bash">npm install rollup --global</code>

For larger teams working on Node.js projects, local installation is recommended for version consistency:

<code class="language-bash">npm install rollup --save-dev</code>

After local installation, use npx rollup to execute commands. Alternatively, define Rollup commands within your package.json scripts:

<code class="language-json">"scripts": {
  "watch": "npx rollup ./src/main.js --file ./build/bundle.js --format es --watch",
  "build": "npx rollup ./src/main.js --file ./build/bundle.js --format es",
  "help": "npx rollup --help"
}</code>

These scripts can be run using npm run watch or npm run build. This tutorial primarily uses npx rollup for broader compatibility.

A Simple Example:

Let's create a basic digital clock example to illustrate Rollup's functionality. You can download example files from GitHub or create them manually.

  • src/main.js: (Main entry point)
<code class="language-javascript">import * as dom from './lib/dom.js';
import { formatHMS } from './lib/time.js';

const clock = dom.get('.clock');

if (clock) {
  console.log('initializing clock');
  setInterval(() => {
    clock.textContent = formatHMS();
  }, 1000);
}</code>
  • src/lib/dom.js: (DOM utility library)
<code class="language-javascript">export function get(selector, doc = document) {
  return doc.querySelector(selector);
}
export function getAll(selector, doc = document) {
  return doc.querySelectorAll(selector);
}</code>
  • src/lib/time.js: (Time formatting functions)
<code class="language-javascript">function timePad(n) {
  return String(n).padStart(2, '0');
}
export function formatHM(d = new Date()) {
  return timePad(d.getHours()) + ':' + timePad(d.getMinutes());
}
export function formatHMS(d = new Date()) {
  return formatHM(d) + ':' + timePad(d.getSeconds());
}</code>
  • index.html: (HTML to display the clock)
<code class="language-html"><!DOCTYPE html>


  <meta charset="UTF-8">
  <title>Rollup.js testing</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">


  <h1>Clock</h1>
  <time class="clock"></time>
  
   
</code>

Quick Start:

To bundle the code, run this command from your project's root directory:

<code class="language-bash">npx rollup ./src/main.js --file ./build/bundle.mjs --format iife</code>

This creates build/bundle.mjs. Note that unused functions are removed through tree-shaking. The index.html references this bundled file.

Key Rollup.js Configuration Options:

  • --file or -o: Specifies the output file name.
  • --format or -f: Defines the output format (iife, es, cjs, umd, amd, system).
  • --sourcemap: Generates a source map for easier debugging (use --sourcemap inline for an inline source map).
  • --watch or -w: Watches for file changes and automatically rebuilds.
  • --config or -c: Uses a configuration file (e.g., rollup.config.js).

Configuration File (rollup.config.js):

A configuration file simplifies managing multiple options and plugins. Here's an example:

<code class="language-bash">npm install rollup --global</code>

Run with: npx rollup --config

Plugins:

Rollup's extensibility comes from its plugin system. Common plugins include:

  • @rollup/plugin-node-resolve: Handles Node.js module resolution.
  • @rollup/plugin-commonjs: Converts CommonJS modules to ES modules.
  • @rollup/plugin-replace: Replaces tokens in your code during the build process.
  • @rollup/plugin-buble: Transpiles ES6 code to ES5 (consider alternatives for modern browser support).
  • rollup-plugin-terser: Minifies the output code.

Remember to install plugins using npm install <plugin-name> --save-dev</plugin-name>. Include them in the plugins array within your rollup.config.js.

Advanced Techniques:

  • Environment Variables: Use environment variables (e.g., NODE_ENV) to conditionally modify your build process (development vs. production).
  • Multiple Bundles: Configure Rollup to generate multiple bundles from different entry points.
  • Code Splitting: Further optimize your application by splitting code into smaller chunks loaded on demand.

Rollup.js provides a powerful and flexible way to bundle your JavaScript modules. By understanding its core features and plugin ecosystem, you can create highly optimized and maintainable JavaScript applications. Remember to consult the official Rollup.js documentation for the most up-to-date information and a comprehensive list of plugins.

The above is the detailed content of An Introduction to the Rollup.js JavaScript Bundler. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn