cleanup(linter): refactor code for dynamic/static imports check (#20897)

This commit is contained in:
Miroslav Jonaš 2024-02-25 17:59:51 +01:00 committed by GitHub
parent 26b266faf4
commit ce933132d0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 34 additions and 10 deletions

View File

@ -32,8 +32,8 @@ import {
isComboDepConstraint,
isDirectDependency,
matchImportWithWildcard,
onlyLoadChildren,
stringifyTags,
hasStaticImportOfDynamicResource,
} from '../utils/runtime-lint-utils';
import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
import { basename, dirname, relative } from 'path';
@ -566,16 +566,14 @@ export default ESLintUtils.RuleCreator(
// if we import a library using loadChildren, we should not import it using es6imports
if (
node.type === AST_NODE_TYPES.ImportDeclaration &&
node.importKind !== 'type' &&
!checkDynamicDependenciesExceptions.some((a) =>
matchImportWithWildcard(a, imp)
) &&
onlyLoadChildren(
hasStaticImportOfDynamicResource(
node,
projectGraph,
sourceProject.name,
targetProject.name,
[]
targetProject.name
)
) {
const filesWithLazyImports = findFilesWithDynamicImports(

View File

@ -22,6 +22,7 @@ import {
resolveModuleByImport,
TargetProjectLocator,
} from '@nx/js/src/internal';
import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
export type Deps = { [projectName: string]: ProjectGraphDependency[] };
type SingleSourceTagConstraint = {
@ -202,17 +203,42 @@ export function findConstraintsFor(
});
}
export function onlyLoadChildren(
export function hasStaticImportOfDynamicResource(
node:
| TSESTree.ImportDeclaration
| TSESTree.ImportExpression
| TSESTree.ExportAllDeclaration
| TSESTree.ExportNamedDeclaration,
graph: ProjectGraph,
sourceProjectName: string,
targetProjectName: string
): boolean {
if (
node.type !== AST_NODE_TYPES.ImportDeclaration ||
node.importKind === 'type'
) {
return false;
}
return onlyLoadChildren(graph, sourceProjectName, targetProjectName, []);
}
function onlyLoadChildren(
graph: ProjectGraph,
sourceProjectName: string,
targetProjectName: string,
visited: string[]
) {
if (visited.indexOf(sourceProjectName) > -1) return false;
if (visited.indexOf(sourceProjectName) > -1) {
return false;
}
return (
(graph.dependencies[sourceProjectName] || []).filter((d) => {
if (d.type !== DependencyType.dynamic) return false;
if (d.target === targetProjectName) return true;
if (d.type !== DependencyType.dynamic) {
return false;
}
if (d.target === targetProjectName) {
return true;
}
return onlyLoadChildren(graph, d.target, targetProjectName, [
...visited,
sourceProjectName,