Enhance Your Rollup Build Process Using Rollup Plugin CommonJS for Better Performance

Introduction to rollup-plugin-commonjs

The `rollup-plugin-commonjs` plugin is an essential tool for developers using Rollup for module bundling. It allows the seamless integration of CommonJS modules in Rollup, enabling the use of npm packages that rely on this module format. This powerful plugin is invaluable for optimizing and modernizing your build processes.

Installation


npm install --save-dev @rollup/plugin-commonjs

Basic Usage

To use the `rollup-plugin-commonjs`, include it in your Rollup configuration:


import commonjs from '@rollup/plugin-commonjs';

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'cjs'
  },
  plugins: [commonjs()]
};

API Explanations

Source Map Support

Enable source maps for better debugging:


commonjs({
  sourceMap: true  // Default: true 
})

Include and Exclude

You can specify which files to include or exclude:


commonjs({
  include: 'node_modules/**',  // Default: undefined
  exclude: ['node_modules/foo/**', 'node_modules/bar/**']  // Default: undefined
})

Transform Mixed Exports

Allow the transformation of mixed ES and CommonJS modules:


commonjs({
  transformMixedEsModules: true  // Default: false
})

Dynamic Require

Enable dynamic require statements:


commonjs({
  dynamicRequireTargets: [ 'node_modules/my-package/**' ]
})

Named Exports

Sometimes, the plugin cannot infer named exports automatically. You can specify them manually:


commonjs({
  namedExports: {
    'node_modules/my-module/index.js': ['foo', 'bar']
  }
})

Example App

Here is an example of how you can build a simple app using `rollup-plugin-commonjs`.

Directory Structure


my-app/
├── node_modules/
├── src/
│   └── index.js
├── dist/
├── rollup.config.js
└── package.json

src/index.js


const _ = require('lodash');

function component() {
  const element = document.createElement('div');
  element.innerHTML = _.join(['Hello', 'world'], ' ');
  return element;
}

document.body.appendChild(component());

rollup.config.js


import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'iife',
    name: 'app'
  },
  plugins: [
    resolve(),
    commonjs()
  ]
};

Running rollup -c will generate a bundle.js file in the dist folder, which you can include in an HTML file to see the app in action.

This example demonstrates how powerful and flexible rollup-plugin-commonjs can be in integrating CommonJS modules seamlessly into your Rollup-based projects, improving both performance and modifiability.

Happy coding!

Hash: 3eefe855f5d8626d5062efe6d8d0ef3df9943f3ae0053ac06f6ebd1b213119b8

Leave a Reply

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