nodejs / nodejs/node

import(cjs) and require(cjs) share a cache

未关闭
#49,453 7 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
122k
派生
37.4k
平均合并
4 天 3 小时
30 天内合并 PR
272

描述

Hiya! 👋

This might very well be on purpose, and if so feel free to close this issue.

For background, I'm currently working on ESM support in Jest. We implement our own resolution and module loading (including caching), so I'm writing some tests to try to make sure our semantics matches node's semantics.

I wrote the following test:

// stateful.cjs
'use strict';

let num = 0;

module.exports = function inc() {
  num++;
  return num;
};
// test.mjs
import * as assert from 'assert';
import {createRequire} from 'module';

async function main() {
  const require = createRequire(import.meta.url);

  const requiredStateful = require('./stateful.cjs');
  // delete require.cache[require.resolve('./stateful.cjs')];
  const {default: importedStateful} = await import('./stateful.cjs');

  assert.equal(importedStateful(), 1);
  assert.equal(importedStateful(), 2);
  assert.equal(requiredStateful(), 1);
  assert.equal(importedStateful(), 3);
  assert.equal(requiredStateful(), 2);
  assert.equal(requiredStateful(), 3);
}

main().catch(err => {
  process.exitCode = 1;

  console.error(err);
});

However, this test fails because the numbers are 1, 2, 3, 4, 5, 6, e.g. they share the same module rather than having their own.

I assumed that the module cache of require and import() would not be shared, based on

require.cache is not used by import. It has a separate cache.

From https://nodejs.org/api/esm.html#esm_no_require_cache

Note that if I swap the order from require then import to import then require (and uncomment the delete), the test behaves like I expect.

So doing import(cjs) populates require.cache which means require(cjs) loads the cached module, and require(cjs) populates the cache so import(cjs) reads it, but doing delete require.cache only affect require, not import.

If import populates and reads from require.cache, I'd expect it do respect deletions from that same property. What I would expect from reading the docs is that import would neither populate nor read from require.cache.

I ran these tests with no flags, using node v13.12.0.


Again, this might be expected behavior, and if so I'd be happy to provide a PR with a docs change specifying this. As a user I find it quite confusing, though

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 ESM 文档中关于独立 require.cache 缓存的部分开始,并在当前 Node.js 版本上复现 issue 的 test.mjs 和 stateful.cjs 示例。确认 import()、require() 与 require.cache 之间观察到的关系,并在该行为符合预期的情况下记录预期行为和删除语义。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, node.js
领域
documentation
Issue 类型
文档
难度
3/5
预计耗时
1-2 天
活跃度
冷清
描述清晰度
基本清楚
新手友好度
48/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。