How to concatenate files using Rollup

Image of two ropes tied or concatenated together

This code defines a Rollup plugin called rollup-plugin-concat to concatenate multiple files into a single output file. It has been built into an npm package that you can find here:

https://www.npmjs.com/package/rollup-plugin-concat

It allows groups of files to be concatenated into a single output file that can then be imported by other JavaScript files further in the bundling cycle.

Here’s a breakdown of what the code does:

const createFilter = require('rollup-pluginutils').createFilter
const fs = require('fs');
const path = require('path');

function concat(options = {}) {
    const filter = createFilter(options.include, options.exclude);
    const groupedFiles = options.groupedFiles || [];

    return {
        name: 'concat',
        buildStart() {
            for (const group of groupedFiles) {
                const files = group.files || [];
                if (typeof group.outputFile === 'undefined') {
                    throw new Error("You must specify an outputFile property.")
                }

                let code = '';

                for (const file of files) {
                    if (filter(file)) {
                        const content = fs.readFileSync(file, 'utf8');
                        code += `${content}\n`;
                    }
                }

                const outputFile = path.resolve(process.cwd(), group.outputFile);
                fs.writeFileSync(outputFile, code, 'utf8');
            }
        },
    };
}

module.exports = concat;

Lines 1-3 import the necessary modules: createFilter from the rollup-pluginutils package, fs (File System) module, and path module.

Line 5 defines the concat function, which takes an options object as a parameter. This object contains configuration options for the plugin.

Inside the concat function, it first initializes a filter variable using createFilter from rollup-pluginutils. This filter is used to include or exclude files based on the options.include and options.exclude properties.

Line 7 assigns the value of options.groupedFiles to the groupedFiles variable. groupedFiles is an array of objects where each object represents a group of files to be concatenated. Each object in groupedFiles should have a files property containing an array of file paths to concatenate and an outputFile property specifying the path of the resulting concatenated file.

The function returns an object that serves as the Rollup plugin. It has a name property(line 10) set to ‘concat’ to identify the plugin.

On line 11, the buildStart hook is defined within the plugin. This hook is called when the build process starts.

Note: Using this specific Rollup hook allows us to concatenate early so that the resulting output files can be imported by the application source code.

Inside this hook, it iterates over each group of files specified in groupedFiles.

  1. For each group, it checks if group.outputFile is defined. If not, it throws an error indicating that an outputFile property must be specified for each set of files to be concatenated.
  2. It initializes an empty code string to store the concatenated content of the files.
  3. It then loops over each file in group.files and checks if the file passes the filter using filter(file). If the file passes the filter, it reads the contents of the file using fs.readFileSync and appends it to the code string.
  4. After concatenating all the files, it resolves the absolute path of the output file using path.resolve and process.cwd() (current working directory).
  5. Finally, it writes the code string to the output file using fs.writeFileSync.
Rollup Usage:

The first thing we need to do is install the plugin using the following command: (making sure node.js is installed first)

npm install --save-dev rollup-plugin-concat

The following is a sample rollup config:

import concat from 'rollup-plugin-concat';

export default {
    input: 'src/index.js',
    output: {
        file: 'bundle.js',
        format: 'esm'
    },
    plugins: [
        concat({
            groupedFiles: [
                {
                    files: ['./fileA.js', './fileB.js'],
                    outputFile: './ab.js',
                },
                {
                    files: ['./fileC.js', './fileD.js'],
                    outputFile: './cd.js',
                },
            ],
        }),
    ],
    //other plugins go here
}

On line 1, we import the plugin from node_modules

On line 10, we add the concat plugin with two groups of files to be concatenated.

For more details see the rollup documentation: https://rollupjs.org

Summary:

In summary, this code defines a Rollup plugin that concatenates specified files into a single output file based on the configuration provided in groupedFiles. The plugin is used at the start of the build process to perform the concatenation. Typically, rollup-plugin-concat should be placed before other plugins so that they may import the concatenated files if needed.