UNPKG

@rushstack/eslint-plugin

Version:

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

52 lines 2.56 kB
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import { parseImportSpecifierFromExpression } from './LintUtilities'; export const MESSAGE_ID = 'error-transitive-dependency-imports'; const NODE_MODULES_PATH_SEGMENT = '/node_modules/'; export const noTransitiveDependencyImportsRule = { defaultOptions: [], meta: { type: 'problem', messages: { [MESSAGE_ID]: 'The specified import targets a transitive dependency.' }, schema: [], docs: { description: 'Prevents referencing imports that are transitive dependencies, ie. imports that are not ' + 'direct dependencies of the package.', url: 'https://www.npmjs.com/package/@rushstack/eslint-plugin' } }, create: (context) => { const checkImportExpression = (importExpression) => { if (!importExpression) { // Can't validate, return return; } const importSpecifier = parseImportSpecifierFromExpression(importExpression); if (importSpecifier === undefined) { // Can't validate, return return; } // Check to see if node_modules is mentioned in the normalized import path more than once if // the path is relative, or if it is mentioned at all if the path is to a package. const { importTarget } = importSpecifier; const isRelative = importTarget.startsWith('.'); let nodeModulesIndex = importTarget.indexOf(NODE_MODULES_PATH_SEGMENT); if (nodeModulesIndex >= 0 && isRelative) { // We allow relative paths to node_modules one layer deep to deal with bypassing exports nodeModulesIndex = importTarget.indexOf(NODE_MODULES_PATH_SEGMENT, nodeModulesIndex + NODE_MODULES_PATH_SEGMENT.length - 1); } if (nodeModulesIndex >= 0) { context.report({ node: importExpression, messageId: MESSAGE_ID }); } }; return { ImportDeclaration: (node) => checkImportExpression(node.source), ImportExpression: (node) => checkImportExpression(node.source), ExportAllDeclaration: (node) => checkImportExpression(node.source), ExportNamedDeclaration: (node) => checkImportExpression(node.source) }; } }; //# sourceMappingURL=no-transitive-dependency-imports.js.map