diff --git a/lib/init/config-file.js b/lib/init/config-file.js index 02e25b63..10c288b5 100644 --- a/lib/init/config-file.js +++ b/lib/init/config-file.js @@ -13,8 +13,10 @@ import path from "path"; import stringify from "json-stable-stringify-without-jsonify"; import debugEsm from "debug"; import { pathToFileURL } from "url"; +import { createRequire } from "module"; const debug = debugEsm("eslint:config-file"); +const require = createRequire(path.join(process.cwd(), "./__placeholder__")); //------------------------------------------------------------------------------ // Helpers @@ -32,6 +34,18 @@ function sortByKey(a, b) { return a.key > b.key ? 1 : -1; } +/** + * import local-installed package + * @param {*} pkgName the package name to import + * @returns {Promise<*>} the exported module + */ +async function importLocalPackage(pkgName) { + const pkgPath = require.resolve(pkgName); + const pkg = await import(pathToFileURL(pkgPath)); // eslint-disable-line node/no-unsupported-features/es-syntax + + return pkg.default; +} + //------------------------------------------------------------------------------ // Private //------------------------------------------------------------------------------ @@ -88,9 +102,7 @@ async function writeJSConfigFile(config, filePath) { // import("eslint") won't work when running npx. // as `@eslint/create-config` was installed in npm-cache, while eslint was installed in cwd. - // TODO: find a safer way to import local-installed modules. - const eslintPath = path.join(process.cwd(), "./node_modules/eslint/lib/api.js"); - const eslint = (await import(pathToFileURL(eslintPath))).default; // eslint-disable-line node/no-unsupported-features/es-syntax + const eslint = await importLocalPackage("eslint"); const linter = new eslint.ESLint({ baseConfig: config, fix: true, useEslintrc: false }); const result = await linter.lintText(stringifiedContent);