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

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

我有 a project 我正在努力获得使用汇总的 UMD、ESM 和 CommonJS 示例的乐趣。 UMD 和 ESM 工作得很好,但对于 CommonJS,我得到...

Uncaught ReferenceError: exports is not defined

CommonJS 输出是...

'use strict';

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

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

exports.SimpleTest = SimpleTest;

HTML 是...

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

导出不会来自 RequireJS 吗?

这是通过将 module 编译器选项设置为 es6 来解决的:

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

让我知道这是否适合您!

您似乎在尝试演示 amd 而不是 cjs。在浏览器上 运行 cjs 没有意义,因为它只适用于节点环境。

您正尝试在浏览器中包含支持 amdrequire.js,因此您只需将 cjs 切换为 amd 即可:

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

如果有人对此感兴趣,请查看我为使 CJS 正常工作所做的工作...

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