JavaScript: module/require 未定义

JavaScript: module/require is not defined

我想让 Jest 测试我在我的网络应用程序前端使用的一些 JavaScript 代码。 据我了解,我需要从我的模块中导出和导入函数,以便我可以在 Jest 中测试它们,而 Jest(仅)支持开箱即用的 CommonJS 模块语法。 结果,我的代码如下所示:

<!-- index.html -->
<!DOCTYPE html>
<html><body><div>Hello World</div>
<script src="./utils.js">
    console.log('foo: ' + foo());
</script>
</body></html>
// utils.js
function foo() {return 42;}
module.exports = {foo};
// __test__/utils.test.js
const utils = require('../utils');
describe('utils', () => {
    test('foo', () => {expect(utils.foo()).toBe(42);});
});

测试部分有效,但是当我在浏览器中打开 index.html 时,我得到

Uncaught ReferenceError: module is not defined

我的理解是前端不支持 CommonJS 模块语法(根据 Client on node: Uncaught ReferenceError: require is not defined)。 我应该如何编写我的 utils.js 文件并导出以便我可以:

  1. utils.js
  2. 的组件进行 Jest 测试
  3. 在浏览器中使用 utils.js 中定义的函数

明确一点,我不想从浏览器运行我的测试。

对于上下文:在我的实际用例中,我 运行 使用 Express 和 Node.js 的应用程序,但这个最小的示例应该捕获潜在的问题。

另请参阅此相关问题:Uncaught ReferenceError: module/require is not defined

尝试检查 module 是否存在:

// utils.js

function foo() { return 42; }

if(module) module.exports = {foo}; // On node.js, use exports
else if(window) window.foo = foo; // In browser, use window
else console.error('Unknown environment');

在浏览器中:

<!-- index.html -->
<!doctype html>
<html>
  <body>
    <script src="./utils.js"></script>
    <script>
      // Use your foo() here!
      console.log('foo: ', window.foo());
    </script>
  </body>
</html>

我在从我的主 js 文件导出时遇到了类似的 jest 错误

以下对我来说效果很好

if (typeof module !== 'undefined') module.exports = { foo };

PS:我已经放弃了 JS 代码的模块化,因为 js 模块会抛出 cors 错误,因为我的 (html, js) 代码在远程到 [=20 的浏览器进程中运行=] 应用程序,更重要的是 html,js 代码从磁盘而不是服务器加载。