Skip to content

Commit 7b9d40d

Browse files
authored
fix(commonjs): fix crash with invalidated proxy modules (#1876)
In watch mode when the code imports CommonJS from ESM, depending on the setup, it can happen that the ES to Commonjs proxy module is re-evaluated. If that happens, its meta information is lost, leading to a weird crash.
1 parent cb1b08d commit 7b9d40d

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

packages/commonjs/src/resolve-require-sources.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ export function getRequireResolver(extensions, detectCyclesAndConditional, curre
141141
return (
142142
(await getTypeForImportedModule(
143143
(
144-
await this.load({ id: resolved.id })
144+
await this.load(resolved)
145145
).meta.commonjs.resolved,
146146
this.load
147147
)) !== IS_WRAPPED_COMMONJS

packages/commonjs/test/test.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1285,6 +1285,48 @@ test('handles external dependencies when using the cache', async (t) => {
12851285
t.is(await getCodeFromBundle(bundle), code);
12861286
});
12871287

1288+
test('Correctly processes meta data when using the cache but invalidating proxy modules', async (t) => {
1289+
const modules = {};
1290+
const resetModules = () => {
1291+
modules['main.js'] = "import first from 'first.js';export default first;";
1292+
modules['first.js'] = "import second from 'second.js';export default second;";
1293+
modules['second.js'] = 'module.exports = 42;';
1294+
};
1295+
const options = {
1296+
input: 'main.js',
1297+
external: ['external'],
1298+
plugins: [
1299+
{
1300+
name: 'test',
1301+
shouldTransformCachedModule({ id }) {
1302+
if (id.endsWith('?commonjs-es-import')) {
1303+
return true;
1304+
}
1305+
return null;
1306+
},
1307+
transform(code, id) {
1308+
if (id.endsWith('?commonjs-es-import')) {
1309+
return `${code}\n//${Date.now()}`;
1310+
}
1311+
return null;
1312+
}
1313+
},
1314+
commonjs(),
1315+
loader(modules)
1316+
],
1317+
onwarn
1318+
};
1319+
1320+
resetModules();
1321+
let bundle = await rollup(options);
1322+
t.is((await executeBundle(bundle, t)).exports, 42);
1323+
1324+
options.cache = bundle.cache;
1325+
modules['main.js'] = "import first from 'first.js';export default first + 1;";
1326+
bundle = await rollup(options);
1327+
t.is((await executeBundle(bundle, t)).exports, 43);
1328+
});
1329+
12881330
test('allows the config to be reused', async (t) => {
12891331
const config = {
12901332
preserveModules: true,

0 commit comments

Comments
 (0)