diff --git a/loader/utils/getModuleSystem.js b/loader/utils/getModuleSystem.js index 0ba67a60..df7d8bbc 100644 --- a/loader/utils/getModuleSystem.js +++ b/loader/utils/getModuleSystem.js @@ -1,8 +1,20 @@ const fs = require('node:fs/promises'); const path = require('node:path'); -/** @type {Map} */ -let packageJsonTypeMap = new Map(); +/** @type {WeakMap>} */ +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. @@ -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 = ''; diff --git a/test/loader/unit/getModuleSystem.test.js b/test/loader/unit/getModuleSystem.test.js index e7f681d3..6b6b475d 100644 --- a/test/loader/unit/getModuleSystem.test.js +++ b/test/loader/unit/getModuleSystem.test.js @@ -1,3 +1,5 @@ +const fs = require('fs/promises'); +const os = require('os'); const path = require('path'); const { ModuleFilenameHelpers } = require('webpack'); @@ -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 }); + } + }); });