Search code examples
javascriptrollup

How to get Rollup to transform require() calls?


I'm trying to build my project using Rollup. I got most of it working (including Angular 2), but I'm unable to transform some of my polyfills, since they have calls to require() in them. Even with the rollup-plugin-node-resolve and rollup-plugin-commonjs it won't touch the requires at all.

So how can I transform them? A workaround I could use is to Browserify the polyfills and then include the browserified bundle in the rollup process, but that requires an awfully lot of extra plugins and isn't exactly a clean solution, especially since I thought that Rollup should be able to understand CommonJS.

Here is some test code for Node.js:

"use strict";
let rollup = require("rollup");
let fs = require("fs");
let resolve = require("rollup-plugin-node-resolve");
let commonjs = require("rollup-plugin-commonjs");

rollup.rollup({
    entry: "src/main.js",
    plugins: [
        resolve({
            jsnext: true,
            main: true
        }),
        commonjs({
            include: '**', // also tried src/** node_modules/** and a lot of other stuff. 
                           // Leaving this undefined stops rollup from working
        }),
    ]
}).then(function(bundle) {
    bundle.write({
        format: "iife",
        dest: "www/bundle.js"
    })
});

Then using a simple file as src/main.js that just contains the line require("./some-file.js"); and a src/some-file.js that contains anything demonstrates the problem.


Solution

  • I solved it with the help of the nice guys at rollup-gitter.

    I needed to add a moduleName to the bundle.write options like so:

    bundle.write({
        format: "iife",
        dest: "www/bundle.js"
        moduleName: "someModule"
    })