From 8b5b86c0db06934facea6993c335bb715467b928 Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Sat, 28 Sep 2019 15:43:58 -0700 Subject: [PATCH] Fix: Load CommonJS .eslintrc.js files within a "type": "module" package scope (fixes #12319) --- lib/cli-engine/config-array-factory.js | 14 ++++++++++++++ package.json | 1 + 2 files changed, 15 insertions(+) diff --git a/lib/cli-engine/config-array-factory.js b/lib/cli-engine/config-array-factory.js index 6e1ba1e02b96..719123d32680 100644 --- a/lib/cli-engine/config-array-factory.js +++ b/lib/cli-engine/config-array-factory.js @@ -36,6 +36,7 @@ const fs = require("fs"); const path = require("path"); const importFresh = require("import-fresh"); +const requireFromString = require("require-from-string"); const stripComments = require("strip-json-comments"); const { validateConfigSchema } = require("../shared/config-validator"); const naming = require("../shared/naming"); @@ -188,6 +189,19 @@ function loadJSConfigFile(filePath) { try { return importFresh(filePath); } catch (e) { + if (e.code === "ERR_REQUIRE_ESM") { + + /* + * The JS config file is a CommonJS .js file within a `"type": "module"`` + * package scope. Node errors when trying to require such a file, + * so bypass Node’s check. There’s no need for `importFresh`, because + * this method never adds the loaded .js file into `require.cache`. + */ + const content = readFile(filePath); + + return requireFromString(content, filePath, { appendPaths: path.dirname(filePath) }); + } + debug(`Error reading JavaScript file: ${filePath}`); e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; throw e; diff --git a/package.json b/package.json index 9ce1c59b0d95..14a489117db8 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "optionator": "^0.8.2", "progress": "^2.0.0", "regexpp": "^2.0.1", + "require-from-string": "^2.0.2", "semver": "^6.1.2", "strip-ansi": "^5.2.0", "strip-json-comments": "^3.0.1",