
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
dynamic-import-resolution
Advanced tools
Dynamically resolves import paths and generates import statements for JavaScript and TypeScript projects. Supports ES Modules, CommonJS, and custom configurations.
Dynamically resolve import paths and generate import statements in JavaScript and TypeScript projects.
dynamic-import-resolution is a powerful, zero-dependency Node.js library that simplifies the process of generating dynamic, correct, and consistent import statements in your JavaScript and TypeScript code. It intelligently determines the relative import path between files based on your project's structure and configuration, eliminating manual path calculations and reducing the risk of broken imports during refactoring or code generation. It supports multiple module systems (ES Modules, CommonJS) and provides extensive customization options. This library is an ideal choice for code generators, build tools, and any situation where you need to programmatically create import statements.
flat, nested, by-type, and completely custom directory structures for your generated files. Adapt the library to your project, not the other way around.../../../ guesswork.import { ... } from '...';import type { ... } from '...';const ... = require('...');PascalCase, camelCase, kebab-case, snake_case, and lowerCase.typeDirMap option.null for unresolvable situations.npm install dynamic-import-resolution --save-dev
# or
bun install dynamic-import-resolution --save-dev
The library provides two main functions: resolveImportPath and generateImportStatement.
resolveImportPathCalculates the relative import path.
import { resolveImportPath, ImportResolutionConfig, ResolveImportPathParams } from 'dynamic-import-resolution';
const config: ImportResolutionConfig = {
outputStructure: 'nested',
typeDirMap: { model: 'models', enum: 'enums' },
fileExtension: '.ts',
baseOutputDir: './src/generated',
baseSourceDir: './src',
fileNameConvention: 'PascalCase'
};
const params: ResolveImportPathParams = {
sourceFilePath: './app/components/UserComponent.ts',
targetName: 'User',
targetType: 'model',
config
};
const relativePath = resolveImportPath(params);
console.log(relativePath); // Output: '../../generated/models/User.ts'
generateImportStatementGenerates the complete import statement.
import { generateImportStatement, ImportResolutionConfig, GenerateImportStatementParams } from 'dynamic-import-resolution';
const config: ImportResolutionConfig = {
outputStructure: 'flat',
fileExtension: '.js',
baseOutputDir: './dist',
fileNameConvention: 'camelCase'
};
const params: GenerateImportStatementParams = {
sourceFilePath: './src/index.js',
targetName: 'myUtility',
targetType: 'util',
config,
statementType: 'javascript-value',
namedExports: ['helperFunction', 'anotherHelper']
};
const importStatement = generateImportStatement(params);
console.log(importStatement); // Output: import { helperFunction, anotherHelper } from './dist/myUtility.js';
ImportResolutionConfigThis interface defines the configuration options for the library.
| Property | Type | Description | Required | Default Value |
|---|---|---|---|---|
outputStructure | 'nested' | 'flat' | 'by-type' | 'custom' | Determines the directory structure of the generated files. See "Output Structures" below. | Yes | - |
typeDirMap | Record<string, string> | Maps target types (e.g., 'model', 'enum') to directory names. Used with nested and by-type structures. | No | - |
fileExtension | string | The file extension for generated files (e.g., '.ts', '.js'). | Yes | - |
baseOutputDir | string | The root directory for all generated files. | Yes | - |
customPathPattern | (targetType: string, targetName: string) => string | A function that defines the output path for a given target type and name. Required when outputStructure is custom. | No | - |
fileNameConvention | 'PascalCase' | 'camelCase' | 'kebab-case' | 'snake_case' | 'lowerCase' | The naming convention for generated files. | No | 'PascalCase' |
baseSourceDir | string | The root directory of your source files. Used to resolve the source file path. Defaults to process.cwd(). | No | process.cwd() |
ResolveImportPathParamsThis interface defines the parameters for the resolveImportPath function.
| Property | Type | Description | Required |
|---|---|---|---|
sourceFilePath | string | The path to the file where the import statement will be generated. | Yes |
targetName | string | The name of the module to be imported. | Yes |
targetType | string | The type of the module (e.g., 'model', 'enum', 'schema'). | Yes |
config | ImportResolutionConfig | The configuration object. | Yes |
GenerateImportStatementParamsThis interface defines the parameters for the generateImportStatement function. It extends ResolveImportPathParams and adds options for specifying the import statement type.
| Property | Type | Description | Required |
|---|---|---|---|
statementType | 'typescript-type' | 'javascript-value' | 'commonjs-require' | The type of import statement to generate. | Yes |
namedExports | string[] | An array of named exports to import (for typescript-type and javascript-value). | No |
defaultExportName | string | The name of the default export (for typescript-type, javascript-value and commonjs-require). | No |
| ... (other props) | From ResolveImportPathParams | All properties from ResolveImportPathParams | Yes |
Both resolveImportPath and generateImportStatement return:
string: The resolved path or generated import statement, respectively.null: If the path cannot be resolved or the statement cannot be generated (e.g., invalid configuration, missing customPathPattern, unsupported statementType).The outputStructure option controls how generated files are organized:
flat: All generated files are placed directly in the baseOutputDir.nested: Files are organized into subdirectories based on typeDirMap. For example, with typeDirMap: { model: 'models', enum: 'enums' }, models would go in baseOutputDir/models and enums in baseOutputDir/enums.by-type: Similar to nested, but the subdirectory structure might have a different root or a slightly different organization. Also uses typeDirMap.custom: You provide a customPathPattern function that takes the targetType and targetName and returns the full output path (relative to baseOutputDir). This offers maximum flexibility.The fileNameConvention option controls the casing of the generated filenames:
MyExampleFile.tsmyExampleFile.tsmy-example-file.tsmy_example_file.tsmyexamplefile.tsconst config: ImportResolutionConfig = {
outputStructure: 'custom',
customPathPattern: (targetType, targetName) => {
return `schemas/${targetType}Schemas/${targetName}Schema.zod.ts`;
},
fileExtension: '.zod.ts',
baseOutputDir: './src/generated',
fileNameConvention: 'PascalCase'
};
const params: ResolveImportPathParams = {
sourceFilePath: './services/apiService.ts',
targetName: 'Order',
targetType: 'model',
config
};
const relativePath = resolveImportPath(params); // '../generated/schemas/modelSchemas/OrderSchema.zod.ts'
const config: ImportResolutionConfig = {
outputStructure: 'flat',
fileExtension: '.cjs',
baseOutputDir: './dist',
};
const params: GenerateImportStatementParams = {
sourceFilePath: './src/index.cjs',
targetName: 'legacyModule',
targetType: 'module',
config,
statementType: 'commonjs-require',
defaultExportName: 'legacy'
};
const importStatement = generateImportStatement(params); // const legacy = require('./dist/LegacyModule.cjs');
// Example 1: Missing customPathPattern with 'custom' outputStructure
const config1: ImportResolutionConfig = {
outputStructure: 'custom', // customPathPattern is required but missing
fileExtension: '.ts',
baseOutputDir: './output',
};
const params1: ResolveImportPathParams = {
sourceFilePath: './src/component.ts',
targetName: 'MyComponent',
targetType: 'component',
config: config1,
};
const result1 = resolveImportPath(params1);
console.log(result1); // Output: null (and a warning in the console)
// Example 2: Invalid outputStructure
const config2: ImportResolutionConfig = {
outputStructure: 'invalid-structure' as any, // Invalid value
fileExtension: '.js',
baseOutputDir: './output',
};
const params2: ResolveImportPathParams = {
sourceFilePath: './src/main.js',
targetName: 'Utils',
targetType: 'util',
config: config2,
};
const result2 = resolveImportPath(params2);
console.log(result2); // Output: null (and a warning in the console)
// Example 3: Invalid statementType
const config3: ImportResolutionConfig = {
outputStructure: 'flat',
fileExtension: '.ts',
baseOutputDir: './output',
};
const params3: GenerateImportStatementParams = {
sourceFilePath: './src/app.ts',
targetName: 'MyModule',
targetType: 'module',
config: config3,
statementType: 'invalid-type' as any, // Invalid value
};
const result3 = generateImportStatement(params3);
console.log(result3); // Output: null (and a warning in the console)
We welcome contributions! Please see CONTRIBUTING.md for details. (Create this file if you want to accept contributions.)
This project is licensed under the MIT License - see the LICENSE file for details.
null return values: Ensure your ImportResolutionConfig is valid, especially outputStructure and customPathPattern (if applicable). Check the console for warnings.baseOutputDir, baseSourceDir, and typeDirMap. Use absolute paths in your configuration if you're unsure.fileNameConvention setting.Q: Can I use this with languages other than JavaScript/TypeScript?
resolveImportPath function could be adapted for other languages if you provide the correct path separators and file extensions in the configuration. Generating import statements would likely require custom logic for other languages.Q: Does this library handle circular dependencies?
dynamic-import-resolution focuses solely on resolving import paths. It does not detect or prevent circular dependencies. You'll need separate tooling (like madge or dependency-cruiser) to manage circular dependencies.Q: Can I use this with a bundler like Webpack or Rollup?
Q: How does this compare to other path resolution libraries?
node_modules). dynamic-import-resolution is designed for static path resolution, primarily for code generation or build-time tasks. It offers more control over the output structure and file naming conventions.Q: Can I use a custom function for fileNameConvention?
fileNameConvention.dynamic imports, import resolution, JavaScript, TypeScript, code generation, build tools, relative paths, module resolution, ES Modules, CommonJS, path manipulation, file naming, code maintainability, refactoring, metaprogramming, static analysis, bun
FAQs
Dynamically resolves import paths and generates import statements for JavaScript and TypeScript projects. Supports ES Modules, CommonJS, and custom configurations.
The npm package dynamic-import-resolution receives a total of 1 weekly downloads. As such, dynamic-import-resolution popularity was classified as not popular.
We found that dynamic-import-resolution demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.