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

Viewed 1598

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?

3 Answers

This is fixed by setting the module compiler option to es6:

  {
  "compilerOptions": {     
    "module": "es6",
    "target": "es5",    
  }
}

Let me know if this works for you!

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`
}

In case anyone is interested here is what I did to get CJS working...

<html>
<body>
<script src="https://cdn.jsdelivr.net/npm/require1k@2.0.0/require1k.min.js"></script>
<script>

    R(function (require, module, exports) {
        const {SimpleTest} = require("./target/ng-demo.cjs");
        new SimpleTest("commonjs");
    });
</script>
</body>
</html>
Related