Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions loader/utils/getModuleSystem.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
const fs = require('node:fs/promises');
const path = require('node:path');

/** @type {Map<string, string | undefined>} */
let packageJsonTypeMap = new Map();
/** @type {WeakMap<object, Map<string, string | undefined>>} */
const compilationPackageJsonTypeMaps = new WeakMap();

function getPackageJsonTypeMap(compilation) {
if (!compilation) return new Map();

let packageJsonTypeMap = compilationPackageJsonTypeMaps.get(compilation);
if (!packageJsonTypeMap) {
packageJsonTypeMap = new Map();
compilationPackageJsonTypeMaps.set(compilation, packageJsonTypeMap);
}

return packageJsonTypeMap;
}

/**
* Infers the current active module system from loader context and options.
Expand Down Expand Up @@ -47,6 +59,8 @@ async function getModuleSystem(ModuleFilenameHelpers, options) {
return 'cjs';
}

const packageJsonTypeMap = getPackageJsonTypeMap(this._compilation);

// We will assume CommonJS if we cannot determine otherwise
let packageJsonType = '';

Expand Down
27 changes: 27 additions & 0 deletions test/loader/unit/getModuleSystem.test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const fs = require('fs/promises');
const os = require('os');
const path = require('path');
const { ModuleFilenameHelpers } = require('webpack');

Expand Down Expand Up @@ -132,4 +134,29 @@ describe('getModuleSystem', () => {
)
).resolves.toBe('cjs');
});

it('should re-read package type for a new compilation', async () => {
const fixturePath = await fs.mkdtemp(path.join(os.tmpdir(), 'react-refresh-module-system-'));
const packageJsonPath = path.join(fixturePath, 'package.json');
const loaderContext = {
resourcePath: path.join(fixturePath, 'index.js'),
rootContext: fixturePath,
addDependency: () => {},
addMissingDependency: () => {},
};

try {
await fs.writeFile(packageJsonPath, JSON.stringify({ type: 'module' }));
await expect(
getModuleSystem.call({ ...loaderContext, _compilation: {} }, ModuleFilenameHelpers, {})
).resolves.toBe('esm');

await fs.writeFile(packageJsonPath, JSON.stringify({ type: 'commonjs' }));
await expect(
getModuleSystem.call({ ...loaderContext, _compilation: {} }, ModuleFilenameHelpers, {})
).resolves.toBe('cjs');
} finally {
await fs.rm(fixturePath, { recursive: true, force: true });
}
});
});