UNPKG

@rushstack/eslint-plugin

Version:

An ESLint plugin providing supplementary rules for use with the @rushstack/eslint-config package

54 lines 2.78 kB
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as path from 'node:path'; import { getRootDirectoryFromContext, getImportAbsolutePathFromExpression } from './LintUtilities'; export const MESSAGE_ID = 'error-external-local-imports'; const _relativePathRegex = /^[.\/\\]+$/; export const noExternalLocalImportsRule = { defaultOptions: [], meta: { type: 'problem', messages: { [MESSAGE_ID]: 'The specified import target "{{ importAbsolutePath }}" is not under the root directory, "{{ rootDirectory }}". Ensure that ' + 'all local import targets are either under the "parserOptions.tsconfigRootDir" specified in your eslint.config.js (if one ' + 'exists) or else under the folder that contains your tsconfig.json.' }, schema: [], docs: { description: 'Prevents referencing relative imports that are either not under the "parserOptions.tsconfigRootDir" specified in ' + 'your eslint.config.js (if one exists) or else not under the folder that contains your tsconfig.json.', url: 'https://www.npmjs.com/package/@rushstack/eslint-plugin' } }, create: (context) => { const rootDirectory = getRootDirectoryFromContext(context); const checkImportExpression = (importExpression) => { if (!importExpression || !rootDirectory) { // Can't validate, return return; } // Get the relative path between the target and the root. If the target is under the root, then the resulting // relative path should be a series of "../" segments. const importAbsolutePath = getImportAbsolutePathFromExpression(context, importExpression); if (!importAbsolutePath) { // Can't validate, return return; } const relativePathToRoot = path.relative(importAbsolutePath, rootDirectory); if (!_relativePathRegex.test(relativePathToRoot)) { context.report({ node: importExpression, messageId: MESSAGE_ID, data: { importAbsolutePath, rootDirectory } }); } }; return { ImportDeclaration: (node) => checkImportExpression(node.source), ImportExpression: (node) => checkImportExpression(node.source), ExportAllDeclaration: (node) => checkImportExpression(node.source), ExportNamedDeclaration: (node) => checkImportExpression(node.source) }; } }; //# sourceMappingURL=no-external-local-imports.js.map