蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 CJS 导出解构缓存、ESM 具名/默认/命名空间严格模式、ESM 导入 CJS、CJS 动态 import 及 Node v24 require(esm)

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-commonjs-esm.mjs
explore-commonjs-esm.mjs150 行
import fsp from 'node:fs/promises';
import { createRequire } from 'node:module';
import os from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

function deepEqual(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'mbsky-node-cjsesm-'));

try {
  const req = createRequire(path.join(tmpDir, 'app.cjs'));

  // Case 1: CommonJS exports (module.exports & exports), destructuring, runtime conditional require & cache
  await fsp.writeFile(
    path.join(tmpDir, 'math.cjs'),
    `function add(a, b) { return a + b; }\nmodule.exports = { add };\n`,
    'utf8',
  );
  await fsp.writeFile(
    path.join(tmpDir, 'user.cjs'),
    `exports.name = 'Alice';\nexports.age = 30;\nexports.sayHello = () => 'Hello, my name is Alice.';\n`,
    'utf8',
  );

  const mathCjs = req('./math.cjs');
  const { name, age, sayHello } = req('./user.cjs');
  const conditionalLoaded = true ? req('./math.cjs') : null;
  const actual1 = {
    sum: mathCjs.add(2, 3),
    user: { name, age, greeting: sayHello() },
    cacheHit: conditionalLoaded === mathCjs,
  };
  const expected1 = {
    sum: 5,
    user: { name: 'Alice', age: 30, greeting: 'Hello, my name is Alice.' },
    cacheHit: true,
  };

  // Case 2: ESM named exports, default export, namespace import & default strict mode
  const mathEsmPath = path.join(tmpDir, 'math.mjs');
  await fsp.writeFile(
    mathEsmPath,
    `export function add(a, b) { return a + b; }\nexport default function multiply(a, b) { return a * b; }\n`,
    'utf8',
  );
  const userEsmPath = path.join(tmpDir, 'user.mjs');
  await fsp.writeFile(
    userEsmPath,
    `export const name = 'Bob';
export const age = 25;
export default function sayHello() { return \`Hello, my name is \${name}.\`; }
export const isStrict = (function () { return this === undefined; })();
`,
    'utf8',
  );

  const mathNs = await import(pathToFileURL(mathEsmPath).href);
  const userNs = await import(pathToFileURL(userEsmPath).href);

  const actual2 = {
    add: mathNs.add(2, 3),
    multiply: mathNs.default(2, 3),
    userName: userNs.name,
    userAge: userNs.age,
    userDefault: userNs.default(),
    esmStrictMode: userNs.isStrict,
    namespaceKeys: Object.keys(userNs).sort(),
  };
  const expected2 = {
    add: 5,
    multiply: 6,
    userName: 'Bob',
    userAge: 25,
    userDefault: 'Hello, my name is Bob.',
    esmStrictMode: true,
    namespaceKeys: ['age', 'default', 'isStrict', 'name'],
  };

  // Case 3: Interop — ESM importing CommonJS module (exposed via default export)
  const cjsInteropPath = path.join(tmpDir, 'commonjs_module.cjs');
  await fsp.writeFile(
    cjsInteropPath,
    `module.exports = { data: 'hello', count: 3 };\n`,
    'utf8',
  );
  const importedCjs = await import(pathToFileURL(cjsInteropPath).href);
  const actual3 = {
    defaultData: importedCjs.default.data,
    defaultCount: importedCjs.default.count,
    hasDefaultExport: typeof importedCjs.default === 'object',
  };
  const expected3 = {
    defaultData: 'hello',
    defaultCount: 3,
    hasDefaultExport: true,
  };

  // Case 4: Interop — CommonJS loading ESM via dynamic import()
  const cjsDynamicLoaderPath = path.join(tmpDir, 'cjs_loads_esm.cjs');
  const userEsmUrl = pathToFileURL(userEsmPath).href;
  await fsp.writeFile(
    cjsDynamicLoaderPath,
    `module.exports = async function loadESM() {
  const mod = await import(${JSON.stringify(userEsmUrl)});
  return { name: mod.name, greeting: mod.default() };
};\n`,
    'utf8',
  );
  const loadEsmFromCjs = req('./cjs_loads_esm.cjs');
  const actual4 = await loadEsmFromCjs();
  const expected4 = { name: 'Bob', greeting: 'Hello, my name is Bob.' };

  // Case 5: Node.js v24 native require(esm) interoperability (sync ESM works; top-level await throws ERR_REQUIRE_ASYNC_MODULE)
  const syncEsmViaRequire = req(userEsmPath);
  const asyncEsmPath = path.join(tmpDir, 'tla_module.mjs');
  await fsp.writeFile(asyncEsmPath, `export const v = await Promise.resolve(99);\n`, 'utf8');
  let tlaErrCode = null;
  try {
    req(asyncEsmPath);
  } catch (err) {
    tlaErrCode = err.code;
  }

  const actual5 = {
    syncRequireEsmName: syncEsmViaRequire.name,
    syncRequireEsmDefault: syncEsmViaRequire.default(),
    tlaRequireErrCode: tlaErrCode,
  };
  const expected5 = {
    syncRequireEsmName: 'Bob',
    syncRequireEsmDefault: 'Hello, my name is Bob.',
    tlaRequireErrCode: 'ERR_REQUIRE_ASYNC_MODULE',
  };

  const cases = [
    { name: 'cjs_exports_and_destructuring', passed: deepEqual(actual1, expected1), expected: expected1, actual: actual1 },
    { name: 'esm_named_default_namespace', passed: deepEqual(actual2, expected2), expected: expected2, actual: actual2 },
    { name: 'esm_imports_cjs_interop', passed: deepEqual(actual3, expected3), expected: expected3, actual: actual3 },
    { name: 'cjs_loads_esm_dynamic_import', passed: deepEqual(actual4, expected4), expected: expected4, actual: actual4 },
    { name: 'node24_require_esm_sync_interop', passed: deepEqual(actual5, expected5), expected: expected5, actual: actual5 },
  ];

  console.log(JSON.stringify({ version: process.version, cases }));
} finally {
  await fsp.rm(tmpDir, { recursive: true, force: true });
}
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/nodejs-commonjs-esm-lab/explore-commonjs-esm.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-commonjs-esm.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Node.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1046.zip

下载课程关联工程包:Node.js

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习