Search code examples
javascriptrolluprollupjs

Why am I getting "Uncaught ReferenceError: exports is not defined" when trying to use Rollup with commonjs?


I have the a project I am working on for fun to get UMD, ESM, and CommonJS examples working with rollup. The UMD and ESM ones work great but for the CommonJS one I am getting...

Uncaught ReferenceError: exports is not defined

The CommonJS output is...

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

class SimpleTest{
    constructor(message){
        console.log(`Your message is ${message}`);
    }
}

exports.SimpleTest = SimpleTest;

The HTML is...

<html>
<body>
<script src="https://requirejs.org/docs/release/2.3.6/comments/require.js"></script>
<script>
    require(["./target/ng-demo.js"], (dep)=>{
        new dep.SimpleTest("ESM");
    });
</script>
</body>
</html>

Wouldn't exports come from RequireJS?


Solution

  • It looks like you're trying to demonstrate amd instead of cjs. It doesn't make sense to run cjs on browser since it only works on node env.

    You're trying to include require.js which supports amd on the browser, so you just simply switch your cjs to amd then it would work:

    {
      file: "./target/ng-demo.js",
      format: "amd" // instead of `cjs`
    }