示例工程 12-umd-systemjs

12-umd-systemjs/01-umd-wrapper/main.js

javascript · 1.7 KB

运行:12 · UMD 包装

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

// main.js —— 同一份 UMD 源码在三种环境下的加载结果
// 测试直接读取 umd-lib.js 的源码,用 new Function 模拟三种全局环境。
 
export function loadAsCjs(source) {
  const module = { exports: {} };
  const fn = new Function('module', 'exports', 'define', 'self', source);
  fn(module, module.exports, undefined, undefined);
  return module.exports;
}
 
export function loadAsAmd(source) {
  let captured;
  const define = (deps, factory) => {
    captured = factory();
  };
  define.amd = {};
  const fn = new Function('module', 'exports', 'define', 'self', source);
  fn(undefined, undefined, define, undefined);
  return captured;
}
 
export function loadAsGlobal(source) {
  const self = {};
  const fn = new Function('self', 'module', 'define', source);
  fn(self, undefined, undefined);
  return self.UmdLib;
}
 
export function run(log = console.log) {
  if (typeof fetch !== 'function') {
    throw new Error('本示例需要浏览器环境:请通过 index.html 打开');
  }
  return fetch('./umd-lib.js')
    .then((res) => res.text())
    .then((source) => {
      const cjs = loadAsCjs(source);
      const amd = loadAsAmd(source);
      const global = loadAsGlobal(source);
 
      const rows = [
        ['CJS:module.exports', `${cjs.version} / add(1,2)=${cjs.add(1, 2)}`],
        ['AMD:define 工厂', `${amd.version} / add(1,2)=${amd.add(1, 2)}`],
        ['global:self.UmdLib', `${global.version} / add(1,2)=${global.add(1, 2)}`],
      ];
      log('环境 => 结果');
      for (const [label, value] of rows) log(`${label} => ${value}`);
      log('-'.repeat(50));
      log('要点:UMD 在运行时依次检测 AMD、CJS、全局,三种环境返回同一份 API。');
      return rows;
    });
}