Search code examples
javascriptreactjsrollup

How to configure Rollup to allow multiple entry points as well as CJS and EJS compilation?


I wish to be able to import my library with multiple entry points (like ABC/X, ABC/Y, ABC/Z). I've been able to do the same with the help of 'rollup-plugin-multi-input' plugin.

But now I also wish to compile it in both ECMA and CommonJS. I've not been able to find any relevant documentation for this, and most results I get are for imports from the library (like import {x} from "abc"). No CJS compilation is creating troubles for me in React testing.

How do you provide multiple entry points at the same time compile in ECMA and CommonJS?


Solution

  • I have this in a couple projects that I bundle for both node and browser environments.

    Optionally, first, in your package.json, make sure that you have a main and module set like so:

    {
        "main": "package-cjs.js",
        "module": "package-esm.js"
    }
    

    This will be used to name the bundles and is a better alternative to hardcoding the names.

    Then, in your rollup.config.js, it should look something like the following (note that I don't know how your input looks like so you can leave yours as it is if it's different).

    import pkg from "./package.json";
    import commonjs from "rollup-plugin-commonjs";
    
    export default {
        input: "./src/index.ts",
        external: [],
        plugins: [
            commonjs(),
        ],
        output: [{
            file: pkg.main,
            format: "cjs",
            exports: 'default'
        }, {
            file: pkg.module,
            format: "esm",
        }],
    };
    

    Note that in the file property of each export we use the name from the package.json. You can also just set this as a string if you don't want to do that step.

    Now when you run your Rollup build you should see bundles for both the main and module.