Path: blob/main/src/rules/no-relative-packages.js
829 views
import path from 'path';1import readPkgUp from 'eslint-module-utils/readPkgUp';23import resolve from 'eslint-module-utils/resolve';4import moduleVisitor, { makeOptionsSchema } from 'eslint-module-utils/moduleVisitor';5import importType from '../core/importType';6import docsUrl from '../docsUrl';78function findNamedPackage(filePath) {9const found = readPkgUp({ cwd: filePath });10if (found.pkg && !found.pkg.name) {11return findNamedPackage(path.join(found.path, '../..'));12}13return found;14}1516function checkImportForRelativePackage(context, importPath, node) {17const potentialViolationTypes = ['parent', 'index', 'sibling'];18if (potentialViolationTypes.indexOf(importType(importPath, context)) === -1) {19return;20}2122const resolvedImport = resolve(importPath, context);23const resolvedContext = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename();2425if (!resolvedImport || !resolvedContext) {26return;27}2829const importPkg = findNamedPackage(resolvedImport);30const contextPkg = findNamedPackage(resolvedContext);3132if (importPkg.pkg && contextPkg.pkg && importPkg.pkg.name !== contextPkg.pkg.name) {33const importBaseName = path.basename(importPath);34const importRoot = path.dirname(importPkg.path);35const properPath = path.relative(importRoot, resolvedImport);36const properImport = path.join(37importPkg.pkg.name,38path.dirname(properPath),39importBaseName === path.basename(importRoot) ? '' : importBaseName,40);41context.report({42node,43message: `Relative import from another package is not allowed. Use \`${properImport}\` instead of \`${importPath}\``,44});45}46}4748module.exports = {49meta: {50type: 'suggestion',51docs: {52url: docsUrl('no-relative-packages'),53},54schema: [makeOptionsSchema()],55},5657create(context) {58return moduleVisitor((source) => checkImportForRelativePackage(context, source.value, source), context.options[0]);59},60};616263