alias-it
v1.0.1
Published
Intelligent TypeScript path mapping with auto-discovery and validation
Maintainers
Readme
alias-it
🚀 Intelligent TypeScript path mapping with auto-discovery and validation
A powerful Node.js/TypeScript package that automatically discovers, generates, and validates path mappings for TypeScript projects. Say goodbye to manual tsconfig.json path configuration!
🎯 What Problem Does This Solve?
Before: You manually maintain tsconfig.json paths every time you add/move folders:
{
"compilerOptions": {
"paths": {
"@components/*": ["src/components/*"],
"@utils/*": ["src/utils/*"],
"@services/*": ["src/services/*"],
"@hooks/*": ["src/hooks/*"],
"@types/*": ["src/types/*"]
}
}
}After: Run one command and it's done automatically:
npx alias-it generate --merge✨ Features
- 🔍 Auto-discovery: Automatically finds TypeScript files and directories in your project
- 🎯 Smart aliasing: Generates meaningful aliases based on file/directory names
- ✅ Validation: Validates existing path mappings and suggests improvements
- 🔧 CLI Interface: Easy-to-use command-line interface with commander
- 📝 tsconfig.json Integration: Seamlessly updates your TypeScript configuration
- 🧪 Conflict Resolution: Intelligently handles alias conflicts
- 💡 Suggestions: Provides intelligent suggestions for better path mappings
🚀 Quick Start
Installation
npm install alias-it
# or
yarn add alias-itBasic Usage
import { PathMapper, generatePathMappings } from "alias-it";
// Quick way to generate mappings
const mappings = await generatePathMappings({
rootDir: "./src",
maxDepth: 3,
});
console.log(mappings);
// Output:
// {
// "@components": "src/components",
// "@utils": "src/utils",
// "@types": "src/types"
// }CLI Usage (New!)
# Discover potential mappings
npx alias-it discover
# Generate and update tsconfig.json
npx alias-it generate --merge
# Validate existing mappings
npx alias-it validate
# Get suggestions
npx alias-it suggest
# See all available commands
npx alias-it --help📖 Real-World Examples
Example 1: Large React Project Setup
Scenario: You have a React project with many folders and want clean imports.
Project Structure:
src/
├── components/
│ ├── Button/
│ ├── Modal/
│ └── Form/
├── hooks/
│ ├── useAuth.ts
│ └── useApi.ts
├── utils/
│ ├── validation.ts
│ └── helpers.ts
├── services/
│ ├── api.ts
│ └── auth.ts
└── types/
└── index.tsBefore: Manual tsconfig.json setup
{
"compilerOptions": {
"paths": {
"@components/*": ["src/components/*"],
"@hooks/*": ["src/hooks/*"],
"@utils/*": ["src/utils/*"],
"@services/*": ["src/services/*"],
"@types/*": ["src/types/*"]
}
}
}After: One command
npx alias-it generate --mergeResult: Clean imports in your code
// Before: Messy relative imports
import Button from "../../../components/Button/Button";
import { useAuth } from "../../../hooks/useAuth";
import { validateEmail } from "../../../utils/validation";
// After: Clean absolute imports
import Button from "@components/Button/Button";
import { useAuth } from "@hooks/useAuth";
import { validateEmail } from "@utils/validation";Example 2: Monorepo Management
Scenario: You have a monorepo with multiple packages and want to share code between them.
Project Structure:
packages/
├── app/
│ └── src/
├── shared/
│ ├── components/
│ └── utils/
├── ui/
│ └── src/
└── types/
└── index.tsCommand:
npx alias-it generate --root-dir packages --mergeResult: Automatic cross-package imports
// In packages/app/src/components/Header.tsx
import { Button } from "@ui/Button";
import { formatDate } from "@shared/utils/date";
import { User } from "@types/User";Example 3: Refactoring Safety
Scenario: You're moving folders around and want to ensure imports don't break.
Before Refactor:
src/
├── components/
└── utils/After Refactor:
src/
├── ui/
│ └── components/
└── common/
└── utils/Command:
npx alias-it generate --mergeResult: All imports automatically updated, no broken references!
Example 4: Validation and Maintenance
Scenario: You want to ensure your path mappings are still valid after team changes.
# Check for broken mappings
npx alias-it validate
# Get suggestions for improvements
npx alias-it suggestOutput:
✅ All path mappings are valid!
Suggestions:
1. Consider adding alias for common directory: @hooks -> src/hooks
2. Consider using shorter path: src/components/Button -> components/Button🛠️ CLI Commands
discover
Discovers potential path mappings in the project.
npx alias-it discover [options]Options:
--root-dir <path>: Root directory to scan (default: current directory)--output <path>: Output file for results (JSON format)
Example:
npx alias-it discover --root-dir ./src --output ./discovered-paths.jsongenerate
Generates path mappings and optionally updates tsconfig.json.
npx alias-it generate [options]Options:
--root-dir <path>: Root directory to scan (default: current directory)--tsconfig <path>: Path to tsconfig.json (default: tsconfig.json)--output <path>: Output file for mappings (JSON format)--merge: Merge with existing mappings (default: true)--no-merge: Replace existing mappings
Examples:
# Generate and merge with existing mappings
npx alias-it generate --merge
# Generate and replace all mappings
npx alias-it generate --no-merge
# Generate for specific directory and save to file
npx alias-it generate --root-dir ./packages --output ./path-mappings.jsonvalidate
Validates existing path mappings in tsconfig.json.
npx alias-it validate [options]Options:
--root-dir <path>: Root directory to scan (default: current directory)--tsconfig <path>: Path to tsconfig.json (default: tsconfig.json)
Example:
npx alias-it validate --tsconfig ./packages/app/tsconfig.jsonsuggest
Gets suggestions for path mappings.
npx alias-it suggest [options]Options:
--root-dir <path>: Root directory to scan (default: current directory)
Example:
npx alias-it suggest --root-dir ./srcupdate
Updates tsconfig.json with new mappings from a file.
npx alias-it update --output <path> [options]Options:
--output <path>: Input file with mappings (JSON format) (required)--tsconfig <path>: Path to tsconfig.json (default: tsconfig.json)--merge: Merge with existing mappings (default: true)--no-merge: Replace existing mappings--root-dir <path>: Root directory to scan (default: current directory)
Example:
npx alias-it update --output ./custom-mappings.json --merge📖 API Reference
PathMapper Class
The main class for path mapping operations.
import { PathMapper } from "alias-it";
const mapper = new PathMapper({
rootDir: "./src",
maxDepth: 3,
includePatterns: ["**/*.ts", "**/*.tsx"],
excludePatterns: ["**/*.d.ts", "**/node_modules/**"],
});Options
| Option | Type | Default | Description |
| ------------------ | ---------- | --------------------------------------------------- | ------------------------------- |
| rootDir | string | process.cwd() | Root directory to scan |
| maxDepth | number | 3 | Maximum directory depth to scan |
| includePatterns | string[] | ['**/*.ts', '**/*.tsx'] | File patterns to include |
| excludePatterns | string[] | ['**/*.d.ts', '**/node_modules/**', '**/dist/**'] | Patterns to exclude |
| autoGenerate | boolean | true | Auto-generate mappings |
| validateExisting | boolean | true | Validate existing mappings |
Methods
discoverPaths()
Discovers potential path mappings in the project.
const discovered = await mapper.discoverPaths();
// Returns: DiscoveredPath[]generateMappings()
Generates path mappings from discovered paths.
const result = await mapper.generateMappings();
// Returns: PathMapperResultvalidateExistingMappings(tsConfigPath?)
Validates existing path mappings in tsconfig.json.
const validation = await mapper.validateExistingMappings("./tsconfig.json");
// Returns: ValidationResultupdateTsConfig(mappings, tsConfigPath?, merge?)
Updates tsconfig.json with new path mappings.
await mapper.updateTsConfig({
"@components": "src/components",
"@utils": "src/utils",
});Convenience Functions
generatePathMappings(options?)
Quick function to generate path mappings.
import { generatePathMappings } from "alias-it";
const mappings = await generatePathMappings({
rootDir: "./src",
});validatePathMappings(tsConfigPath?, options?)
Quick function to validate existing mappings.
import { validatePathMappings } from "alias-it";
const isValid = await validatePathMappings("./tsconfig.json");updateTsConfigMappings(mappings, tsConfigPath?, merge?, options?)
Quick function to update tsconfig.json.
import { updateTsConfigMappings } from "alias-it";
await updateTsConfigMappings({
"@components": "src/components",
});🔧 Development Workflow
For New Projects
- Initialize your TypeScript project
- Run the mapper:
npx alias-it generate --merge - Start coding with clean imports!
For Existing Projects
- Validate current mappings:
npx alias-it validate - Get suggestions:
npx alias-it suggest - Update mappings:
npx alias-it generate --merge
For CI/CD Integration
# .github/workflows/validate-paths.yml
name: Validate Path Mappings
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "18"
- run: npm install
- run: npx alias-it validate📁 Project Structure
alias-it/
├── src/
│ ├── types/
│ │ └── index.ts # TypeScript type definitions
│ ├── utils/
│ │ └── fileUtils.ts # File system utilities
│ ├── PathMapper.ts # Main PathMapper class
│ ├── index.ts # Main exports
│ ├── cli.ts # CLI interface (commander-based)
│ └── __tests__/
│ └── PathMapper.test.ts # Tests
├── package.json
├── tsconfig.json
├── jest.config.js
├── .eslintrc.js
└── README.md🧪 Testing
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm test -- --coverage🔧 Development
# Install dependencies
yarn install
# Build the project
yarn build
# Run in development mode
yarn dev
# Lint the code
yarn lint
# Fix linting issues
yarn lint:fix🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Inspired by the need for better TypeScript path management
- Built with modern TypeScript practices
- Tested with Jest for reliability
- CLI powered by Commander.js
📞 Support
If you have any questions or need help, please open an issue on GitHub or contact the maintainers.
Made with ❤️ for the TypeScript community
🚀 Releasing (for Maintainers)
This project uses release-it for automated versioning, changelogs, GitHub releases, and npm publishing.
To create a new release:
Make sure your working directory is clean and on the
mainbranch.Run:
yarn release- This will:
- Prompt for the next version
- Run tests and build
- Update the version in
package.json - Generate/update
CHANGELOG.md - Commit, tag, push, create a GitHub release, and publish to npm
- This will:
To generate or update the changelog only:
yarn changelogNote: You must have
NPM_TOKENandGITHUB_TOKENset in your environment or repository secrets for CI/CD.
