UNPKG

eslint-plugin-path

Version:

An ESLint plugin for enforcing consistent imports across project. In other words, it helps to replace all relatives import with absolutes dependinng on settings.

85 lines 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../utils"); const import_types_1 = require("../utils/import-types"); const path_1 = require("path"); /** * Creates an absolute path to target using an array of alias items * @param target - The target path to convert to absolute * @param aliases - An array of alias items for path resolution * @returns The absolute path import */ function getAbsolutePathToTarget(target, aliases = []) { if (!target || !aliases.length) { return ""; } const absolutePath = aliases .map(({ path, alias }) => `${alias || ""}${(0, path_1.relative)(path, target)}`) .filter(path => !(0, import_types_1.isRelativeToParent)(path) && !path.includes("..")); return absolutePath[0] || ""; } /** * Replace all backslashes (\) with forward slashes (/) * @param path - The path to normalize * @returns The normalized path with forward slashes */ function replaceBackSlashesWithForward(path) { if (!path) { return ""; } return path.replace(/\\/g, "/"); } /** * ESLint rule for enforcing absolute imports * @param context - The rule context * @returns Rule listener object */ function onlyAbsoluteImportsCreate(context) { return (0, utils_1.getImport)(context, ({ node, start, value: current, end, path, packagePath, configSettings, }) => { var _a; if ((0, import_types_1.isExternalPath)(current, packagePath) || !path) { return; } const expected = replaceBackSlashesWithForward(getAbsolutePathToTarget(path, ((_a = configSettings[0]) === null || _a === void 0 ? void 0 : _a.aliases) || [])); if (current === expected || !expected) { return; } const data = { current, expected, }; const fix = (fixer) => fixer.replaceTextRange([start + 1, end - 1], expected); context.report({ node, messageId: "noRelativeImports", data, fix, suggest: [ { messageId: "replaceRelativeImport", data, fix, }, ], }); }); } const rule = { meta: { type: "problem", docs: { description: "disallow relative imports of files where absolute is preferred", url: "https://github.com/qDanik/eslint-plugin-path/blob/main/docs/rules/only-absolute-imports.md", }, fixable: "code", hasSuggestions: true, schema: [], messages: { noRelativeImports: "Relative import path '{{current}}' should be replaced with '{{expected}}'", replaceRelativeImport: "Replace relative import path '{{current}}' with absolute '{{expected}}'", }, }, create: onlyAbsoluteImportsCreate, }; exports.default = rule; //# sourceMappingURL=only-absolute-imports.js.map