Utilities for managing imports, exports, and module resolution in generated code, supporting both CommonJS and ESM patterns. These tools handle the complex task of generating proper import statements for TypeScript code with support for fragments, external types, and various module systems.
Core functions for generating TypeScript import statements with support for different import patterns and module resolution.
/**
* Generates import statement from import declaration configuration
* @param statement - Import declaration configuration
* @returns Generated TypeScript import statement
*/
function generateImportStatement(statement: ImportDeclaration): string;
/**
* Generates fragment import statement with kind-specific formatting
* @param statement - Fragment import declaration configuration
* @param kind - Declaration kind (type, interface, etc.)
* @returns Generated TypeScript import statement for fragments
*/
function generateFragmentImportStatement(statement: ImportDeclaration<FragmentImport>, kind: string): string;
/**
* Resolves relative import paths between modules
* @param from - Source file path
* @param to - Target file path
* @returns Relative import path string
*/
function resolveRelativeImport(from: string, to: string): string;
/**
* Resolves import source configuration to actual import path
* @param source - Import source configuration
* @returns Resolved import path string
*/
function resolveImportSource(source: ImportSource): string;Type definitions for configuring import statements and module resolution.
/**
* Import declaration configuration with module and property information
*/
interface ImportDeclaration<T = {}> {
/** Module name or path to import from */
moduleName: string | null;
/** Property/export name to import */
propName: string;
/** Whether this is a default import */
default?: boolean;
/** Whether this is a namespace import */
namespace?: boolean;
/** Additional import-specific configuration */
} & T;
/**
* Import source configuration for module resolution
*/
interface ImportSource {
/** File path or module name */
path: string;
/** Namespace for the import */
namespace?: string;
/** Whether to use default import */
default?: boolean;
/** Custom import name/alias */
importName?: string;
}
/**
* Fragment import specific configuration
*/
interface FragmentImport {
/** Fragment name */
fragmentName: string;
/** GraphQL type the fragment is on */
onType: string;
/** Whether the fragment is external */
isExternal: boolean;
/** Module to import fragment from */
importFrom?: string;
}Helper functions for resolving module paths and handling different module systems.
/**
* Resolves module path relative to current file
* @param currentFile - Current file path
* @param targetModule - Target module path
* @returns Resolved relative path
*/
function resolveModulePath(currentFile: string, targetModule: string): string;
/**
* Normalizes import path for cross-platform compatibility
* @param importPath - Raw import path
* @returns Normalized import path
*/
function normalizeImportPath(importPath: string): string;
/**
* Checks if a module path is external (node_modules) or internal (relative)
* @param modulePath - Module path to check
* @returns True if module is external
*/
function isExternalModule(modulePath: string): boolean;
/**
* Gets file extension for import path based on module type
* @param filePath - File path
* @param moduleType - Module system (esm, cjs)
* @returns Appropriate file extension
*/
function getImportExtension(filePath: string, moduleType: 'esm' | 'cjs'): string;Classes and utilities for collecting and managing imports throughout code generation.
/**
* Collects and manages import statements during code generation
*/
class ImportCollector {
/**
* Adds an import to the collection
* @param importDecl - Import declaration to add
*/
addImport(importDecl: ImportDeclaration): void;
/**
* Adds a fragment import to the collection
* @param fragmentImport - Fragment import declaration to add
*/
addFragmentImport(fragmentImport: ImportDeclaration<FragmentImport>): void;
/**
* Adds a type import to the collection
* @param typeImport - Type import declaration to add
* @param useTypeImports - Whether to use 'import type' syntax
*/
addTypeImport(typeImport: ImportDeclaration, useTypeImports: boolean): void;
/**
* Gets all collected imports as import statement strings
* @returns Array of import statement strings
*/
getImports(): string[];
/**
* Gets imports grouped by module
* @returns Object with imports grouped by module name
*/
getImportsByModule(): { [moduleName: string]: ImportDeclaration[] };
/**
* Clears all collected imports
*/
clear(): void;
/**
* Merges imports from another collector
* @param other - Other import collector to merge from
*/
merge(other: ImportCollector): void;
}
/**
* Configuration for import collection and generation
*/
interface ImportCollectorConfig {
/** Whether to use 'import type' syntax for types */
useTypeImports: boolean;
/** Whether to emit legacy CommonJS imports */
emitLegacyCommonJSImports: boolean;
/** Whether to prefer default imports */
preferDefaultImports: boolean;
/** Custom import path transformations */
importPathTransform?: (path: string) => string;
}Specialized functions for handling specific import scenarios like mappers, scalars, and external types.
/**
* Builds import statement for mapper types
* @param source - Mapper source configuration
* @param types - Array of type names to import
* @param useTypeImports - Whether to use type imports
* @returns Generated import statement
*/
function buildMapperImport(source: string, types: string[], useTypeImports: boolean): string;
/**
* Builds import statements for scalar types
* @param scalars - Scalars configuration
* @param useTypeImports - Whether to use type imports
* @returns Array of import statements for scalars
*/
function buildScalarImports(scalars: ParsedScalarsMap, useTypeImports: boolean): string[];
/**
* Builds import statements for enum types
* @param enums - Enum configuration
* @param useTypeImports - Whether to use type imports
* @returns Array of import statements for enums
*/
function buildEnumImports(enums: ParsedEnumValuesMap, useTypeImports: boolean): string[];
/**
* Resolves external type import configuration
* @param externalType - External type reference
* @returns Import declaration for external type
*/
function resolveExternalTypeImport(externalType: string): ImportDeclaration;
/**
* Checks if a type reference is external (requires import)
* @param typeRef - Type reference string
* @returns True if type is external
*/
function isExternalTypeReference(typeRef: string): boolean;Usage Examples:
import {
generateImportStatement,
generateFragmentImportStatement,
ImportCollector,
buildMapperImport
} from "@graphql-codegen/visitor-plugin-common";
// Generate basic import statement
const importStmt = generateImportStatement({
moduleName: 'graphql',
propName: 'GraphQLSchema'
});
// Result: import { GraphQLSchema } from 'graphql';
// Generate default import
const defaultImport = generateImportStatement({
moduleName: 'lodash',
propName: 'default',
default: true
});
// Result: import lodash from 'lodash';
// Generate fragment import
const fragmentImport = generateFragmentImportStatement({
moduleName: './fragments',
propName: 'UserFragment',
fragmentName: 'UserFragment',
onType: 'User',
isExternal: true
}, 'type');
// Result: import type { UserFragment } from './fragments';
// Use ImportCollector
const collector = new ImportCollector({
useTypeImports: true,
emitLegacyCommonJSImports: false
});
collector.addImport({ moduleName: 'graphql', propName: 'GraphQLSchema' });
collector.addTypeImport({ moduleName: './types', propName: 'User' }, true);
const imports = collector.getImports();
// Result: ['import { GraphQLSchema } from "graphql";', 'import type { User } from "./types";']
// Build mapper import
const mapperImport = buildMapperImport(
'./mappers#UserMapper',
['UserMapper', 'PostMapper'],
true
);
// Result: import type { UserMapper, PostMapper } from './mappers';Advanced utilities for resolving import paths in different environments and build systems.
/**
* Resolves import path based on project configuration
* @param from - Source file path
* @param to - Target file or module
* @param options - Resolution options
* @returns Resolved import path
*/
function resolveImportPath(from: string, to: string, options?: {
baseUrl?: string;
paths?: { [key: string]: string[] };
extensions?: string[];
}): string;
/**
* Handles TypeScript path mapping resolution
* @param importPath - Import path to resolve
* @param pathMappings - TypeScript path mappings
* @returns Resolved path or original if no mapping found
*/
function resolvePathMapping(importPath: string, pathMappings: { [key: string]: string[] }): string;
/**
* Converts absolute import to relative import
* @param absolutePath - Absolute import path
* @param currentFile - Current file path
* @returns Relative import path
*/
function toRelativeImport(absolutePath: string, currentFile: string): string;
/**
* Ensures import path has appropriate file extension
* @param importPath - Import path
* @param extension - File extension to ensure
* @returns Import path with extension
*/
function ensureImportExtension(importPath: string, extension: string): string;Advanced Usage Examples:
// Complex import collection with custom configuration
class CustomCodeGenerator {
private imports = new ImportCollector({
useTypeImports: true,
emitLegacyCommonJSImports: false,
preferDefaultImports: false,
importPathTransform: (path) => path.replace(/\.ts$/, '.js')
});
generateCode() {
// Add various types of imports
this.imports.addImport({
moduleName: 'graphql',
propName: 'GraphQLObjectType'
});
this.imports.addTypeImport({
moduleName: './types',
propName: 'User'
}, true);
this.imports.addFragmentImport({
moduleName: './fragments',
propName: 'UserFragment',
fragmentName: 'UserFragment',
onType: 'User',
isExternal: true
});
// Generate final code with imports
const imports = this.imports.getImports().join('\n');
const code = this.generateTypeDefinitions();
return `${imports}\n\n${code}`;
}
}
// Path resolution with custom configuration
const resolvedPath = resolveImportPath(
'./src/generated/types.ts',
'@/utils/helpers',
{
baseUrl: './src',
paths: {
'@/*': ['./src/*'],
'@utils/*': ['./src/utils/*']
}
}
);