Skip to content

Commit

Permalink
fix: safer import
Browse files Browse the repository at this point in the history
  • Loading branch information
aladdin-add committed Dec 17, 2021
1 parent f3f949b commit 3a6c875
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions lib/init/config-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -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);

Expand Down

0 comments on commit 3a6c875

Please sign in to comment.