From b52a49460a6b87bb13b98d8ffb07a17dd129590f Mon Sep 17 00:00:00 2001 From: Josh Story Date: Tue, 5 Sep 2023 10:33:25 -0700 Subject: [PATCH] use cjs form for webpack4 because it does not support `import.meta`. Instead of feature testing with `this.environment` which was added to webpack 5 relatively recently use `typeof this.addMissingDepdencey === 'function'` which is in most (or all) webpack 5 releases but not included in webpack 4. --- loader/utils/getModuleSystem.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/loader/utils/getModuleSystem.js b/loader/utils/getModuleSystem.js index 41eaed4f..0a217834 100644 --- a/loader/utils/getModuleSystem.js +++ b/loader/utils/getModuleSystem.js @@ -41,6 +41,12 @@ async function getModuleSystem(ModuleFilenameHelpers, options) { if (/\.mjs$/.test(this.resourcePath)) return 'esm'; if (/\.cjs$/.test(this.resourcePath)) return 'cjs'; + if (typeof this.addMissingDependency !== 'function') { + // This is Webpack 4 which does not support `import.meta` and cannot use ESM anwyay. We assume .js files + // are commonjs because the output cannot be ESM anyway + return 'cjs'; + } + // We will assume commonjs if we cannot determine otherwise let packageJsonType = ''; @@ -104,10 +110,7 @@ async function getModuleSystem(ModuleFilenameHelpers, options) { } catch (e) { // package.json does not exist. We track it as a missing dependency so we can reload if this // file is added - if (typeof this.addMissingDependency === 'function') { - // Webpack 4 does not have this method - this.addMissingDependency(packageJsonPath); - } + this.addMissingDependency(packageJsonPath); } // try again at the next level up