Path Alias
Path Alias is a module import path mapping mechanism that allows developers to use short, semantic identifiers to replace complete module paths. In Esmx, the path alias mechanism provides the following advantages:
- Simplify Import Paths: Use semantic aliases to replace lengthy relative paths, improving code readability.
- Avoid Deep Nesting: Eliminate maintenance difficulties caused by multi-level directory references (like
../../../../). - Type Safety: Fully integrated with TypeScript's type system, providing code completion and type checking.
- Module Resolution Optimization: Improve module resolution performance through predefined path mappings.
Default Alias Mechanism
Esmx adopts an automatic alias mechanism based on Service Name. This convention-over-configuration design has the following characteristics:
- Automatic Configuration: Automatically generates aliases based on the
namefield inpackage.json, no manual configuration needed. - Unified Specification: Ensures all service modules follow consistent naming and reference specifications.
- Type Support: Works with
npm run build:dtscommand to automatically generate type declaration files, enabling cross-service type inference. - Predictability: Module reference paths can be inferred through service name, reducing maintenance costs.
Configuration Instructions
package.json Configuration
In package.json, define the service name through the name field, which will serve as the default alias prefix for the service:
tsconfig.json Configuration
To enable TypeScript to correctly resolve alias paths, configure paths mapping in tsconfig.json:
Usage Examples
Import Internal Service Modules
Import Other Service Modules
Best Practices
Prefer Alias Paths
In business code, alias paths should be preferred over relative paths:
Maintain Semantics and Consistency
- Prefer alias paths over relative paths.
- Keep alias paths semantic and consistent.
- Avoid using too many directory levels in alias paths.
Cross-Service Import
When module linking is configured, you can import modules from other services in the same way:
Custom Aliases
For third-party packages or special scenarios, you can customize aliases through Esmx configuration files:
- For business modules, it's recommended to always use the default alias mechanism to maintain project consistency.
- Custom aliases are mainly used to handle special needs of third-party packages or optimize development experience.
- Overuse of custom aliases may affect code maintainability and build optimization.