示例工程 11-commonjs

11-commonjs/01-cjs-shim/index.html

html · 0.8 KB

运行:11 · 浏览器里的 CommonJS shim

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>11 · 浏览器里的 CommonJS shim</title>
</head>
<body>
  <p>打开 Console 查看一个最小 CommonJS 运行时如何工作。</p>
  <script type="module">
    import { createCjsRuntime, run } from './main.js';
 
    const { require } = createCjsRuntime({
      './math': (module, exports) => {
        exports.add = (a, b) => a + b;
      },
      './app': (module, exports, require) => {
        const math = require('./math');
        exports.answer = math.add(20, 22);
      }
    });
 
    console.log('require("./app").answer =>', require('./app').answer);
    console.log('第二次 require 命中缓存 =>', require('./app') === require('./app'));
    run();
  </script>
</body>
</html>